diff --git a/.gitignore b/.gitignore index c47d9057..6f86d28b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ .vscode/settings.json .DS_Store rubixcorejava.jar +tests/thunder-tests/thunderActivity.db +tests/thunder-tests/thunderclient.db +tests/thunder-tests/thunderCollection.db +tests/thunder-tests/thunderEnvironment.db diff --git a/src/com/rubix/AuthenticateNode/Authenticate.java b/src/com/rubix/AuthenticateNode/Authenticate.java index c26a8b44..866cc40b 100644 --- a/src/com/rubix/AuthenticateNode/Authenticate.java +++ b/src/com/rubix/AuthenticateNode/Authenticate.java @@ -1,41 +1,54 @@ package com.rubix.AuthenticateNode; -import io.ipfs.api.IPFS; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.json.JSONException; -import org.json.JSONObject; +import static com.rubix.Resources.Functions.DATA_PATH; +import static com.rubix.Resources.Functions.IPFS_PORT; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.getValues; +import static com.rubix.Resources.Functions.nodeData; +import static com.rubix.Resources.Functions.randomPositions; +import static com.rubix.Resources.Functions.strToIntArray; +import static com.rubix.Resources.Functions.syncDataTable; -import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; -import static com.rubix.Resources.Functions.*; +import javax.imageio.ImageIO; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONException; +import org.json.JSONObject; + +import io.ipfs.api.IPFS; public class Authenticate { public static Logger AuthenticateLogger = Logger.getLogger(Authenticate.class); + public static int verifyCount = 0; /** - * This method is used to authenticate a node in Rubix implementing text based two level NLSS. - *

It is customized for 32 positions verification. The position can be changed by + * This method is used to authenticate a node in Rubix implementing text based + * two level NLSS. + *

+ * It is customized for 32 positions verification. The position can be changed + * by * modifying the numberofpositions for integer array sizes accordingly + * * @param detailString Details for verification * @return boolean returns true if verified and false if not verified - * @throws IOException handles IO Exception + * @throws IOException handles IO Exception * @throws JSONException handles JSON Exception */ public static boolean verifySignature(String detailString) throws IOException, JSONException { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + verifyCount++; IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); - System.out.println(IPFS_PORT); JSONObject details = new JSONObject(detailString); String decentralizedID = details.getString("did"); String hash = details.getString("hash"); String signature = details.getString("signature"); - + syncDataTable(decentralizedID, null); String walletIdIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", decentralizedID); nodeData(decentralizedID, walletIdIpfsHash, ipfs); @@ -48,7 +61,7 @@ public static boolean verifySignature(String detailString) throws IOException, J int[] SenderSign = strToIntArray(signature); JSONObject P = randomPositions("verifier", hash, 32, SenderSign); int[] posForSign = (int[]) P.get("posForSign"); - int[] originalPos =(int[]) P.get("originalPos"); + int[] originalPos = (int[]) P.get("originalPos"); for (int positionsLevelTwoTrail : posForSign) senderWalletID.append(walletID.charAt(positionsLevelTwoTrail)); @@ -59,9 +72,9 @@ public static boolean verifySignature(String detailString) throws IOException, J positionsLevelZero[k] = ((originalPos[k]) / 8); StringBuilder decentralizedIDForAuth = new StringBuilder(); - for (int value : positionsLevelZero) decentralizedIDForAuth.append(senderDIDBin.charAt(value)); + for (int value : positionsLevelZero) + decentralizedIDForAuth.append(senderDIDBin.charAt(value)); if (recombinedResult.equals(decentralizedIDForAuth.toString())) { - AuthenticateLogger.info("Verification True"); return true; } else { AuthenticateLogger.info("Verification Failed"); @@ -71,4 +84,3 @@ public static boolean verifySignature(String detailString) throws IOException, J } } - diff --git a/src/com/rubix/AuthenticateNode/Interact.java b/src/com/rubix/AuthenticateNode/Interact.java index 6fad2b02..12d5fc2e 100644 --- a/src/com/rubix/AuthenticateNode/Interact.java +++ b/src/com/rubix/AuthenticateNode/Interact.java @@ -1,67 +1,62 @@ package com.rubix.AuthenticateNode; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; +import static com.rubix.Resources.Functions.LOGGER_PATH; import java.awt.image.BufferedImage; import java.io.IOException; -import static com.rubix.Resources.Functions.LOGGER_PATH; - +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; -public class Interact -{ - public String privateShare = "", candidateShare = "",bits; +public class Interact { + public String privateShare = "", candidateShare = "", bits; public static BufferedImage privateImage, walletImage; - public StringBuilder pvt,cnd; + public StringBuilder pvt, cnd; public int[][] candidateArray; public int[][] secret; public static Logger InteractLogger = Logger.getLogger(Interact.class); - /** * Constructor for setting the secret string + * * @param inputSecret Secret string */ - Interact(String inputSecret){ - bits = inputSecret ; + Interact(String inputSecret) { + bits = inputSecret; } /** * This method creates two shares using NLSS (1,2,2) + * * @return Returns a boolean yes if shares are created successfully * @throws IOException handles IO Exception */ public boolean createShare() throws IOException { PropertyConfigurator.configure(LOGGER_PATH + "log4jDID.properties"); - bits=bits.replaceAll("\\s+",""); - secret= new int[bits.length()][8]; + bits = bits.replaceAll("\\s+", ""); + secret = new int[bits.length()][8]; candidateArray = new int[bits.length()][8]; SecretShare share; pvt = new StringBuilder(); cnd = new StringBuilder(); - for(int i = 0; i < bits.length(); i++) - { - if(bits.charAt(i)=='0') - { + for (int i = 0; i < bits.length(); i++) { + if (bits.charAt(i) == '0') { share = new SecretShare(0); share.starts(); - for(int j=0;j<8;j++) { + for (int j = 0; j < 8; j++) { secret[i][j] = SecretShare.S0[j]; candidateArray[i][j] = SecretShare.Y1[j]; pvt.append(SecretShare.S0[j]); cnd.append(SecretShare.Y1[j]); } } - if(bits.charAt(i)=='1') - { + if (bits.charAt(i) == '1') { share = new SecretShare(1); share.starts(); - for(int j=0;j<8;j++) - { - secret[i][j]= SecretShare.S0[j]; - candidateArray[i][j]= SecretShare.Y1[j]; + for (int j = 0; j < 8; j++) { + secret[i][j] = SecretShare.S0[j]; + candidateArray[i][j] = SecretShare.Y1[j]; pvt.append(SecretShare.S0[j]); cnd.append(SecretShare.Y1[j]); } @@ -74,17 +69,16 @@ public boolean createShare() throws IOException { return checkShare(); } - /** * This method combines the two shares to verify is the split is right or not * * @throws IOException handles IO Exceptions */ public boolean checkShare() throws IOException { - int i,j,sum; + int i, j, sum; boolean verified = true; - for(i=0;i s) { + int sum = 5; + while (sum > s) { sum = 0; for (i = 0; i < cand.length; i++) sum = sum + (cand[i] * S0[i]); - sum=sum%2; - if (sum != s) //if not valid + sum = sum % 2; + if (sum != s) // if not valid { - cand = generateArray(V8, 8); //get new Y - cand = checkComply(cand, S0); //check new Y + cand = generateArray(V8, 8); // get new Y + cand = checkComply(cand, S0); // check new Y } } return cand; } + public void starts() { - public void starts() - { + X1 = generateArray(V4, 4); + alpha1 = generateArray(LA, 8); - X1 = generateArray(V4,4); - alpha1 = generateArray(LA,8); - - Y1 = generateArray(V8,8); - // Y2 = genarray(V8,8); + Y1 = generateArray(V8, 8); + // Y2 = genarray(V8,8); int[] tempmat; - tempmat = multiplyMatrices(X1,G,4,8); + tempmat = multiplyMatrices(X1, G, 4, 8); S0 = new int[tempmat.length]; - for(i=0;i quorumWithShares = new ArrayList<>(); - public static volatile int[] quorumResponse = {0, 0, 0}; + public static volatile int[] quorumResponse = { 0, 0, 0 }; public static volatile JSONArray finalQuorumSignsArray = new JSONArray(); /** @@ -50,7 +49,8 @@ private static synchronized boolean voteNCount(int i, int quorumSize) { synchronized (countLock) { if (quorumResponse[i] < minQuorum(quorumSize)) { quorumResponse[i]++; - InitiatorConsensusLogger.debug("quorum response added index " + i + " is " + quorumResponse[i] + " quorumsize " + minQuorum(quorumSize)); + InitiatorConsensusLogger.debug("quorum response added index " + i + " is " + quorumResponse[i] + + " quorumsize " + minQuorum(quorumSize)); status = true; } else { status = false; @@ -60,18 +60,20 @@ private static synchronized boolean voteNCount(int i, int quorumSize) { return status; } - /** - * This method stores all the quorum signatures until required count for consensus + * This method stores all the quorum signatures until required count for + * consensus * * @param quorumDID DID of the Quorum * @param quorumSignResponse Signature of the Quorum */ - private static synchronized void quorumSign(String quorumDID, String hash, String quorumSignResponse, int index, int quorumSize, int alphaSize) { + private static synchronized void quorumSign(String quorumDID, String hash, String quorumSignResponse, int index, + int quorumSize, int alphaSize) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); synchronized (signLock) { try { - if (quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7)) && quorumResponse[index] <= minQuorum(quorumSize)) { + if (quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7)) + && quorumResponse[index] <= minQuorum(quorumSize)) { JSONObject jsonObject = new JSONObject(); jsonObject.put("did", quorumDID); jsonObject.put("sign", quorumSignResponse); @@ -88,7 +90,6 @@ private static synchronized void quorumSign(String quorumDID, String hash, Strin } } - /** * This method runs the consensus * 1. Contact quorum with sender signatures and details @@ -98,9 +99,10 @@ private static synchronized void quorumSign(String quorumDID, String hash, Strin * @param ipfs IPFS instance * @param PORT Port for forwarding to Quorum */ - public static JSONObject start(String data, IPFS ipfs, int PORT, int index, String role, JSONArray quorumPeersObject, int alphaSize, int quorumSize) throws JSONException { + public static JSONObject start(String data, IPFS ipfs, int PORT, int index, String role, + JSONArray quorumPeersObject, int alphaSize, int quorumSize) throws JSONException { String[] qResponse = new String[QUORUM_COUNT]; - String[] qVerification = new String[QUORUM_COUNT]; + // String[] qVerification = new String[QUORUM_COUNT]; Socket[] qSocket = new Socket[QUORUM_COUNT]; PrintStream[] qOut = new PrintStream[QUORUM_COUNT]; BufferedReader[] qIn = new BufferedReader[QUORUM_COUNT]; @@ -110,6 +112,7 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri String hash = dataObject.getString("hash"); JSONArray details = dataObject.getJSONArray("details"); quorumResponse[index] = 0; + InitiatorConsensusLogger.debug("quorum peer role " + role + " length " + quorumPeersObject.length()); JSONArray tokenDetails; try { tokenDetails = new JSONArray(details.toString()); @@ -132,101 +135,67 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri try { swarmConnectP2P(quorumID[j], ipfs); - String quorumDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", quorumID[j]); - String quorumWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "peerid", quorumID[j]); + syncDataTable(null, quorumID[j]); + String quorumDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", + quorumID[j]); + String quorumWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "peerid", + quorumID[j]); nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); String appName = quorumID[j].concat(role); + InitiatorConsensusLogger.debug("quourm ID " + quorumID[j] + " appname " + appName); forward(appName, PORT + j, quorumID[j]); - InitiatorConsensusLogger.debug("Connected to " + quorumID[j] + "on port " + (PORT + j) + "with AppName" + appName); + InitiatorConsensusLogger.debug( + "Connected to " + quorumID[j] + "on port " + (PORT + j) + "with AppName" + appName); qSocket[j] = new Socket("127.0.0.1", PORT + j); qIn[j] = new BufferedReader(new InputStreamReader(qSocket[j].getInputStream())); qOut[j] = new PrintStream(qSocket[j].getOutputStream()); - qOut[j].println("qstcmrequest"); - qVerification[j] = qIn[j].readLine(); - JSONObject quorumDetails = new JSONObject(qVerification[j]); - String cmData = IPFSNetwork.get(quorumDetails.getString("CreditMapping"), ipfs); - - JSONObject qstContent = new JSONObject(quorumDetails.getString("QuorumSignedTransactions")); - - -// if (qstContent.length() == 0 && role == "alpha") { -// InitiatorConsensusLogger.warn("Alpha quorum (" + quorumID[j] + ") has no credits"); -// } -// if (cmContent.length() == 0 && role == "alpha") { -// InitiatorConsensusLogger.warn("Alpha quorum (" + quorumID[j] + ") has no credits in credit mapping data"); -// } - - if (!qstContent.has("minestatus") && qstContent.length() != 0) { - if (!qstContent.toString().contains("empty")) { - JSONArray cmContent = new JSONArray(cmData); - String credits = qstContent.getString("credits"); - - String creditContent = IPFSNetwork.get(credits, ipfs); - JSONArray credObject = new JSONArray(creditContent); - for (int k = 0; k < credObject.length(); k++) { - JSONObject object = credObject.getJSONObject(k); - String did = object.getString("did"); - String sign = object.getString("sign"); - String signHash = object.getString("hash"); - - JSONObject hashedCredObject = new JSONObject(); - hashedCredObject.put("did", did); - hashedCredObject.put("hash", signHash); - hashedCredObject.put("signature", sign); - - - if (!(Authenticate.verifySignature(hashedCredObject.toString()))) - InitiatorConsensusLogger.warn("Credit verification failed for Alpha quorum (" + quorumID[j] + ") credits"); - - - if (cmContent != null) { - for (int l = 0; l < cmContent.length(); l++) { - if ((cmContent.getJSONObject(l).getString("hash") == signHash)) { - InitiatorConsensusLogger.warn("Credit verification failed for Alpha quorum (" + quorumID[j] + ") credits - Hash matched in Credits Mapping file"); - } - } - } - - } - } - } - qOut[j].println(detailsToken); qResponse[j] = qIn[j].readLine(); if (qResponse[j].equals("Auth_Failed")) { IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } else { - InitiatorConsensusLogger.debug("Signature Received from " + quorumID[j]); + InitiatorConsensusLogger + .debug("Signature Received from " + quorumID[j] + " " + qResponse[j]); if (quorumResponse[index] > minQuorum(quorumSize)) { qOut[j].println("null"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } else { - String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", quorumID[j]); + String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", + quorumID[j]); JSONObject detailsToVerify = new JSONObject(); detailsToVerify.put("did", didHash); detailsToVerify.put("hash", hash); detailsToVerify.put("signature", qResponse[j]); if (Authenticate.verifySignature(detailsToVerify.toString())) { + InitiatorConsensusLogger.debug(role + " node authenticated at index " + index); boolean voteStatus = voteNCount(index, quorumSize); if (quorumResponse[index] <= minQuorum(quorumSize) && voteStatus) { + InitiatorConsensusLogger + .debug("waiting for " + quorumSize + " +signs " + role); while (quorumResponse[index] < minQuorum(quorumSize)) { } + InitiatorConsensusLogger + .debug("between Q1- to Q" + quorumSize + " for index " + index); quorumSign(didHash, hash, qResponse[j], index, quorumSize, alphaSize); quorumWithShares.add(quorumPeersObject.getString(j)); while (quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { } - - qOut[j].println(finalQuorumSignsArray); + InitiatorConsensusLogger.debug("sending Qsign of length " + + quorumSignature.length() + "at index " + index); + qOut[j].println(finalQuorumSignsArray.toString()); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } else { - + InitiatorConsensusLogger.debug("sending null for slow quorum "); qOut[j].println("null"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } - InitiatorConsensusLogger.debug("Quorum Count : " + quorumResponse + "Signature count : " + quorumSignature.length()); + InitiatorConsensusLogger.debug("Quorum Count : " + quorumResponse + + "Signature count : " + quorumSignature.length()); } else { - InitiatorConsensusLogger.debug("node failed authentication with index " + index + " with role " + role + " with did " + didHash + " and data to verify " + detailsToVerify); + InitiatorConsensusLogger.debug("node failed authentication with index " + index + + " with role " + role + " with did " + didHash + " and data to verify " + + detailsToVerify); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } } @@ -240,10 +209,10 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri quorumThreads[j].start(); } - while (quorumResponse[index] < minQuorum(quorumSize) || quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { + while (quorumResponse[index] < minQuorum(quorumSize) + || quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { } repo(ipfs); - } catch (JSONException e) { InitiatorConsensusLogger.error("JSON Exception Occurred", e); e.printStackTrace(); diff --git a/src/com/rubix/Consensus/InitiatorProcedure.java b/src/com/rubix/Consensus/InitiatorProcedure.java index 5d26d05f..412286a6 100644 --- a/src/com/rubix/Consensus/InitiatorProcedure.java +++ b/src/com/rubix/Consensus/InitiatorProcedure.java @@ -1,18 +1,23 @@ package com.rubix.Consensus; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.calculateHash; +import static com.rubix.Resources.Functions.getSignFromShares; +import static com.rubix.Resources.Functions.minQuorum; + +import java.io.IOException; + import com.rubix.Constants.ConsensusConstants; import com.rubix.SplitandStore.SeperateShares; import com.rubix.SplitandStore.Split; -import io.ipfs.api.IPFS; + import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import java.io.IOException; - -import static com.rubix.Resources.Functions.*; +import io.ipfs.api.IPFS; public class InitiatorProcedure { public static String essential; @@ -24,106 +29,179 @@ public class InitiatorProcedure { /** * This function sets up the initials before the consensus + * * @param data Data required for hashing and signing * @param ipfs IPFS instance * @param PORT port for forwarding to quorum */ - public static void consensusSetUp(String data,IPFS ipfs, int PORT,int alphaSize) throws JSONException { + public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSize) throws JSONException { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + JSONObject dataSend = new JSONObject(); + JSONObject dataObject = new JSONObject(data); String tid = dataObject.getString("tid"); - String message = dataObject.getString("message"); - String receiverDidIpfs = dataObject.getString("receiverDidIpfs"); String pvt = dataObject.getString("pvt"); String senderDidIpfs = dataObject.getString("senderDidIpfs"); - String token = dataObject.getString("token"); JSONArray alphaList = dataObject.getJSONArray("alphaList"); JSONArray betaList = dataObject.getJSONArray("betaList"); JSONArray gammaList = dataObject.getJSONArray("gammaList"); - String authSenderByQuorumHash="", authQuorumHash=""; - authSenderByQuorumHash = message; - authQuorumHash = calculateHash(authSenderByQuorumHash.concat(receiverDidIpfs), "SHA3-256"); - - try { - payload.put("sender", senderDidIpfs); - payload.put("token", token); - payload.put("receiver", receiverDidIpfs); - payload.put("tid", tid); - } catch (JSONException e) { - InitiatorProcedureLogger.error("JSON Exception occurred", e); - e.printStackTrace(); - } - Split.split(payload.toString()); - - int[][] shares = Split.get135Shares(); - InitiatorProcedureLogger.debug("Payload Split Success"); - essential = SeperateShares.getShare(shares, payload.toString().length(), 0); - String Q1Share = SeperateShares.getShare(shares, payload.toString().length(), 1); - String Q2Share = SeperateShares.getShare(shares, payload.toString().length(), 2); - String Q3Share = SeperateShares.getShare(shares, payload.toString().length(), 3); - String Q4Share = SeperateShares.getShare(shares, payload.toString().length(), 4); - JSONObject data1 = new JSONObject(); - JSONObject data2 = new JSONObject(); - try { - senderSignQ = getSignFromShares(pvt, authSenderByQuorumHash); - data1.put("sign", senderSignQ); - data1.put("senderDID", senderDidIpfs); - data1.put(ConsensusConstants.TRANSACTION_ID, tid); - data1.put(ConsensusConstants.HASH, authSenderByQuorumHash); - data1.put(ConsensusConstants.RECEIVERID, receiverDidIpfs); - - data2.put("Share1", Q1Share); - data2.put("Share2", Q2Share); - data2.put("Share3", Q3Share); - data2.put("Share4", Q4Share); - } catch (JSONException | IOException e) { - InitiatorProcedureLogger.error("JSON Exception occurred", e); - e.printStackTrace(); + if (dataObject.getString(ConsensusConstants.TRANS_TYPE) == ConsensusConstants.PRIMARY) { + + String message = dataObject.getString("message"); + String receiverDidIpfs = dataObject.getString("receiverDidIpfs"); + String token = dataObject.getString("token"); + + String authSenderByQuorumHash = "", authQuorumHash = ""; + authSenderByQuorumHash = calculateHash(message, "SHA3-256"); + authQuorumHash = calculateHash(authSenderByQuorumHash.concat(receiverDidIpfs), "SHA3-256"); + + InitiatorProcedureLogger.debug("Sender by Quorum Hash" + authSenderByQuorumHash); + InitiatorProcedureLogger.debug("Quorum Auth Hash" + authQuorumHash); + + try { + payload.put("sender", senderDidIpfs); + payload.put("token", token); + payload.put("receiver", receiverDidIpfs); + payload.put("tid", tid); + } catch (JSONException e) { + InitiatorProcedureLogger.error("JSON Exception occurred", e); + e.printStackTrace(); + } + + Split.split(payload.toString()); + + int[][] shares = Split.get135Shares(); + InitiatorProcedureLogger.debug("Payload Split Success"); + essential = SeperateShares.getShare(shares, payload.toString().length(), 0); + String Q1Share = SeperateShares.getShare(shares, payload.toString().length(), 1); + String Q2Share = SeperateShares.getShare(shares, payload.toString().length(), 2); + String Q3Share = SeperateShares.getShare(shares, payload.toString().length(), 3); + String Q4Share = SeperateShares.getShare(shares, payload.toString().length(), 4); + JSONObject data1 = new JSONObject(); + JSONObject data2 = new JSONObject(); + try { + senderSignQ = getSignFromShares(pvt, authSenderByQuorumHash); + data1.put("sign", senderSignQ); + data1.put("senderDID", senderDidIpfs); + data1.put(ConsensusConstants.TRANSACTION_ID, tid); + data1.put(ConsensusConstants.HASH, authSenderByQuorumHash); + data1.put(ConsensusConstants.RECEIVERID, receiverDidIpfs); + + data2.put("Share1", Q1Share); + data2.put("Share2", Q2Share); + data2.put("Share3", Q3Share); + data2.put("Share4", Q4Share); + } catch (JSONException | IOException e) { + InitiatorProcedureLogger.error("JSON Exception occurred", e); + e.printStackTrace(); + } + + JSONArray detailsForQuorum = new JSONArray(); + detailsForQuorum.put(data1); + detailsForQuorum.put(data2); + + InitiatorProcedureLogger.debug("Invoking Consensus"); + dataSend.put("hash", authQuorumHash); + dataSend.put("details", detailsForQuorum); + } - JSONArray detailsForQuorum = new JSONArray(); - detailsForQuorum.put(data1); - detailsForQuorum.put(data2); + if (dataObject.getString(ConsensusConstants.TRANS_TYPE) == ConsensusConstants.DATA) { - InitiatorProcedureLogger.debug("Invoking Consensus"); + String blockHash = dataObject.getString("blockHash"); + String authSenderByQuorumHash = "", authQuorumHash = ""; + authSenderByQuorumHash = calculateHash(blockHash, "SHA3-256"); + authQuorumHash = calculateHash(authSenderByQuorumHash.concat(blockHash), "SHA3-256"); - JSONObject dataSend = new JSONObject(); - dataSend.put("hash",authQuorumHash); - dataSend.put("details",detailsForQuorum); + InitiatorProcedureLogger.debug("Sender by Quorum Hash" + + authSenderByQuorumHash); + InitiatorProcedureLogger.debug("Quorum Auth Hash" + authQuorumHash); + + try { + payload.put("sender", senderDidIpfs); + payload.put("blockHash", blockHash); + payload.put("tid", tid); + } catch (JSONException e) { + InitiatorProcedureLogger.error("JSON Exception occurred", e); + e.printStackTrace(); + } + + Split.split(payload.toString()); + + int[][] shares = Split.get135Shares(); + InitiatorProcedureLogger.debug("Payload Split Success"); + essential = SeperateShares.getShare(shares, payload.toString().length(), 0); + String Q1Share = SeperateShares.getShare(shares, payload.toString().length(), 1); + String Q2Share = SeperateShares.getShare(shares, payload.toString().length(), 2); + String Q3Share = SeperateShares.getShare(shares, payload.toString().length(), 3); + String Q4Share = SeperateShares.getShare(shares, payload.toString().length(), 4); + JSONObject data1 = new JSONObject(); + JSONObject data2 = new JSONObject(); + try { + senderSignQ = getSignFromShares(pvt, authSenderByQuorumHash); + data1.put("sign", senderSignQ); + data1.put("senderDID", senderDidIpfs); + data1.put("blockHash", blockHash); + data1.put(ConsensusConstants.TRANSACTION_ID, tid); + data1.put(ConsensusConstants.HASH, authSenderByQuorumHash); + + data2.put("Share1", Q1Share); + data2.put("Share2", Q2Share); + data2.put("Share3", Q3Share); + data2.put("Share4", Q4Share); + } catch (JSONException | IOException e) { + InitiatorProcedureLogger.error("JSON Exception occurred", e); + e.printStackTrace(); + } + + JSONArray detailsForQuorum = new JSONArray(); + detailsForQuorum.put(data1); + detailsForQuorum.put(data2); + InitiatorProcedureLogger.debug("Invoking Consensus"); + dataSend.put("hash", authQuorumHash); + dataSend.put("details", detailsForQuorum); - Thread alphaThread = new Thread(()->{ + } + + Thread alphaThread = new Thread(() -> { try { - alphaReply = InitiatorConsensus.start(dataSend.toString(),ipfs,PORT,0,"alpha",alphaList,alphaSize,alphaSize); + alphaReply = InitiatorConsensus.start(dataSend.toString(), ipfs, PORT, 0, "alpha", alphaList, alphaSize, + alphaSize); } catch (JSONException e) { e.printStackTrace(); } }); - Thread betaThread = new Thread(()->{ + Thread betaThread = new Thread(() -> { try { - betaReply = InitiatorConsensus.start(dataSend.toString(),ipfs,PORT+100,1,"beta",betaList,alphaSize,7); + betaReply = InitiatorConsensus.start(dataSend.toString(), ipfs, PORT + 100, 1, "beta", betaList, + alphaSize, 7); } catch (JSONException e) { e.printStackTrace(); } }); - Thread gammaThread = new Thread(()->{ + Thread gammaThread = new Thread(() -> { try { - gammaReply = InitiatorConsensus.start(dataSend.toString(),ipfs,PORT+107,2,"gamma",gammaList,alphaSize,7); + gammaReply = InitiatorConsensus.start(dataSend.toString(), ipfs, PORT + 107, 2, "gamma", gammaList, + alphaSize, 7); } catch (JSONException e) { e.printStackTrace(); } }); - InitiatorConsensus.quorumSignature=new JSONObject(); + InitiatorConsensus.quorumSignature = new JSONObject(); + InitiatorConsensus.finalQuorumSignsArray = new JSONArray(); alphaThread.start(); betaThread.start(); gammaThread.start(); - while (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2* minQuorum(7))) {} - InitiatorProcedureLogger.debug("ABG Consensus completed with length " +InitiatorConsensus.quorumSignature.length()); + while (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { + } + InitiatorProcedureLogger + .debug("ABG Consensus completed with length " + InitiatorConsensus.quorumSignature.length()); } } diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index e10ae9a3..59770aac 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,54 +1,75 @@ package com.rubix.Consensus; +import static com.rubix.Constants.ConsensusConstants.DATA; +import static com.rubix.Constants.ConsensusConstants.PRIMARY; +import static com.rubix.Constants.ConsensusConstants.TRANS_TYPE; +import static com.rubix.Resources.Functions.DATA_PATH; +import static com.rubix.Resources.Functions.IPFS_PORT; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.WALLET_DATA_PATH; +import static com.rubix.Resources.Functions.calculateHash; +import static com.rubix.Resources.Functions.deleteFile; +import static com.rubix.Resources.Functions.getPeerID; +import static com.rubix.Resources.Functions.getSignFromShares; +import static com.rubix.Resources.Functions.getValues; +import static com.rubix.Resources.Functions.nodeData; +import static com.rubix.Resources.Functions.syncDataTable; +import static com.rubix.Resources.Functions.updateJSON; +import static com.rubix.Resources.Functions.writeToFile; +import static com.rubix.Resources.IPFSNetwork.add; +import static com.rubix.Resources.IPFSNetwork.listen; +import static com.rubix.Resources.IPFSNetwork.pin; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.ServerSocket; +import java.net.Socket; + import com.rubix.AuthenticateNode.Authenticate; -import com.rubix.AuthenticateNode.PropImage; import com.rubix.Resources.IPFSNetwork; -import io.ipfs.api.IPFS; + import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.ArrayList; -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.Functions.deleteFile; -import static com.rubix.Resources.IPFSNetwork.*; +import io.ipfs.api.IPFS; public class QuorumConsensus implements Runnable { - public static Logger QuorumConsensusLogger = Logger.getLogger(QuorumConsensus.class); - /** * This method is used to run a thread for Quorum Members - *

This involves

  1. Verify sender signature
  2. + *

    + * This involves + *

      + *
    1. Verify sender signature
    2. *
    3. Signing the transaction
    4. - *
    5. Receiving share from sender
    + *
  3. Receiving share from sender
  4. + *
*/ - int port; IPFS ipfs; String role; int round; - public QuorumConsensus(String role,int port){ + public QuorumConsensus(String role, int port) { this.role = role; this.port = port; - this.ipfs=new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + this.ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); } @Override public void run() { while (true) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - boolean integrityCheck=true; - String temp, peerID, transactionID, verifySenderHash, receiverDID, receiverPID, appName, senderPrivatePos, senderDidIpfsHash="", senderPID = ""; + String peerID, transactionID, verifySenderHash, appName; ServerSocket serverSocket = null; Socket socket = null; try { @@ -59,170 +80,295 @@ public void run() { listen(appName, port); - QuorumConsensusLogger.debug("Quorum Listening on " + port + " appname "+appName); - serverSocket = new ServerSocket(port); - socket = serverSocket.accept(); + QuorumConsensusLogger.debug("Quorum Listening on " + port + " appname " + appName); + serverSocket = new ServerSocket(port); + socket = serverSocket.accept(); - BufferedReader dataReq = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - PrintStream dataResp = new PrintStream(socket.getOutputStream()); PrintStream out = new PrintStream(socket.getOutputStream()); - JSONObject readSenderData; - String getData; - String qstReq; - - //? check for incoming request for QST + Thread validate = new ValidationHandler(socket, in, out, ipfs, peerID, didHash, appName); + validate.start(); - qstReq = dataReq.readLine(); - if (qstReq.contains("qstcmrequest")) { + } catch (IOException e) { + QuorumConsensusLogger.error("IOException Occurred", e); + } catch (NullPointerException e) { + QuorumConsensusLogger.error("NullPointer Exception Occurred ", e); + } + } - QuorumConsensusLogger.debug("Sender reqesting QuorumSignedTransactions.json and CreditMapping.json: " + qstReq); + } +} - File creditsMapping = new File(WALLET_DATA_PATH + "CreditMapping.json"); - if(!creditsMapping.exists()) { - QuorumConsensusLogger.debug("File doesn't exist"); - creditsMapping.createNewFile(); - writeToFile(creditsMapping.toString(), "[]", false); - } - JSONArray qstContent = new JSONArray(readFile(WALLET_DATA_PATH + "QuorumSignedTransactions.json")); - JSONObject qstObjectSend = new JSONObject(); - if(qstContent.length() > 0) - qstObjectSend = qstContent.getJSONObject(qstContent.length() - 1); +class ValidationHandler extends Thread { + + public static Logger ValidationHandler = Logger.getLogger(ValidationHandler.class); + + final Socket socket; + final BufferedReader in; + final PrintStream out; + final IPFS ipfs; + final String peerID; + final String didHash; + final String appName; + + public ValidationHandler(Socket socket, BufferedReader in, PrintStream out, IPFS ipfs, String peerID, + String didHash, + String appName) { + this.socket = socket; + this.in = in; + this.out = out; + this.ipfs = ipfs; + this.peerID = peerID; + this.didHash = didHash; + this.appName = appName; + this.start(); + } - String cmFileHash = IPFSNetwork.add(WALLET_DATA_PATH + "CreditMapping.json", ipfs); + boolean integrityCheck = true; + String temp = ""; + String transactionID = ""; + String verifySenderHash = ""; + String blockHash = ""; + String senderPrivatePos = ""; + String senderDidIpfsHash = ""; + String senderPID = ""; + String getData = ""; + String receiverDID = ""; - JSONObject qResponse = new JSONObject(); - qResponse.put("QuorumSignedTransactions", qstObjectSend.toString()); - qResponse.put("CreditMapping", cmFileHash); + JSONObject readSenderData; - dataResp.println(qResponse.toString()); - } + public void run() { + while (true) { - //TODO: if the incoming request contains the keyword "request", push the QST to IPFS and send the two hashes back to the sender. + try { - //? This is where quorum fetched the data send from initiatorConsensus (Line 148) + String getData; + // TODO: check if initiator is sending ping check to see if it is alive getData = in.readLine(); if (getData.contains("ping check")) { - QuorumConsensusLogger.debug("Ping check from sender: " + getData); + ValidationHandler.debug("Ping check from sender: " + getData); out.println("pong response"); - } - else { - QuorumConsensusLogger.debug("Received Details from initiator: " + getData); + } else { + ValidationHandler.debug("Received Details from initiator: " + getData); readSenderData = new JSONObject(getData); senderPrivatePos = readSenderData.getString("sign"); senderDidIpfsHash = readSenderData.getString("senderDID"); transactionID = readSenderData.getString("Tid"); verifySenderHash = readSenderData.getString("Hash"); - receiverDID = readSenderData.getString("RID"); - senderPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", senderDidIpfsHash); - receiverPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", receiverDID); + syncDataTable(senderDidIpfsHash, null); - String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", senderDidIpfsHash); + senderPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", senderDidIpfsHash); + String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", + senderDidIpfsHash); nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); - String quorumHash = calculateHash(verifySenderHash.concat(receiverDID), "SHA3-256"); JSONObject detailsToVerify = new JSONObject(); detailsToVerify.put("did", senderDidIpfsHash); detailsToVerify.put("hash", verifySenderHash); detailsToVerify.put("signature", senderPrivatePos); + writeToFile(LOGGER_PATH + "tempverifysenderhash", verifySenderHash, false); + String verifySenderIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "tempverifysenderhash", ipfs); + deleteFile(LOGGER_PATH + "tempverifysenderhash"); + + // QuorumConsensusLogger.debug("Checking providers for: " + verifySenderHash); + // ArrayList dhtOwnersList = dhtOwnerCheck(verifySenderHash); + // QuorumConsensusLogger.debug("Providers: " + dhtOwnersList); + // boolean consensusIDcheck = false; + // if(dhtOwnersList.size() <= 2 && dhtOwnersList.contains(senderPID)) + // consensusIDcheck = true; + + // if for data, primary or secondary token condition starts here + + if (readSenderData.getString(TRANS_TYPE) == DATA) { + + blockHash = readSenderData.getString("blockHash"); + String quorumHash = calculateHash(verifySenderHash.concat(blockHash), "SHA3-256"); + + if (Authenticate.verifySignature(detailsToVerify.toString())) { + ValidationHandler.debug("Quorum Authenticated Sender"); + + ValidationHandler.debug("ConsensusID pass"); + String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + quorumHash); + + out.println(QuorumSignature); + String creditval; + creditval = in.readLine(); + ValidationHandler.debug("credit value " + creditval); + + if (!creditval.equals("null")) { + + // ? quorum pinning blockHash and files from sender + IPFSNetwork.pin(blockHash, ipfs); + + String blockHashData = IPFSNetwork.get(blockHash, ipfs); + JSONObject blockDataObject = new JSONObject(blockHashData); + JSONArray blockArray = new JSONArray(blockDataObject.getJSONObject("metadata")); + + for (int i = 0; i < blockArray.length(); i++) { + JSONObject blockObject = blockArray.getJSONObject(i); + String blockFileHash = blockObject.getString("file_uid"); + IPFSNetwork.pin(blockFileHash, ipfs); + } + + FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); + shareWriter.write(creditval); + shareWriter.close(); + File readCredit = new File(LOGGER_PATH + "mycredit.txt"); + String credit = add(readCredit.toString(), ipfs); + pin(credit, ipfs); + // adding credit to credit mapping + JSONArray CreditBody = new JSONArray(creditval); + // JSONObject creditMappingObject = new JSONObject(); + JSONArray creditMappingArray = new JSONArray(); + + for (int i = 0; i < CreditBody.length(); i++) { + JSONObject creditMappingObject = new JSONObject(); + JSONObject object = CreditBody.getJSONObject(i); + String key = object.getString("did"); + String sign = object.getString("sign"); + String creditHash = calculateHash(sign, "SHA3-256"); + + creditMappingObject.put("did", key); + creditMappingObject.put("sign", sign); + creditMappingObject.put("hash", creditHash); + creditMappingObject.put("tid", transactionID); + + creditMappingArray.put(creditMappingObject); + + } + writeToFile(WALLET_DATA_PATH + "CreditMapping.json", creditMappingArray.toString(), + false); + + JSONObject storeDetailsQuorum = new JSONObject(); + storeDetailsQuorum.put("tid", transactionID); + storeDetailsQuorum.put("consensusID", verifySenderHash); + storeDetailsQuorum.put("sign", senderPrivatePos); + storeDetailsQuorum.put("credits", credit); + storeDetailsQuorum.put("senderdid", senderDidIpfsHash); + storeDetailsQuorum.put("blockHash", blockHash); + JSONArray data = new JSONArray(); + data.put(storeDetailsQuorum); + ValidationHandler.debug("Quorum Share: " + credit); + updateJSON("add", WALLET_DATA_PATH + "QuorumSignedTransactions.json", data.toString()); + deleteFile(LOGGER_PATH + "mycredit.txt"); + writeToFile(LOGGER_PATH + "consenusIDhash", verifySenderHash, false); + String consenusIDhash = IPFSNetwork.add(LOGGER_PATH + "consenusIDhash", ipfs); + deleteFile(LOGGER_PATH + "consenusIDhash"); + ValidationHandler.debug("added consensus ID " + consenusIDhash); + + } else { + JSONObject storeDetailsQuorum = new JSONObject(); + storeDetailsQuorum.put("tid", transactionID); + storeDetailsQuorum.put("consensusID", verifySenderHash); + storeDetailsQuorum.put("sign", senderPrivatePos); + storeDetailsQuorum.put("credits", ""); + storeDetailsQuorum.put("senderdid", senderDidIpfsHash); + storeDetailsQuorum.put("blockHash", blockHash); + JSONArray data = new JSONArray(); + data.put(storeDetailsQuorum); + updateJSON("add", WALLET_DATA_PATH + "QuorumSignedTransactions.json", data.toString()); + } - QuorumConsensusLogger.debug("Checking providers for: " + verifySenderHash); - ArrayList dhtOwnersList = dhtOwnerCheck(verifySenderHash); - QuorumConsensusLogger.debug("Providers: " + dhtOwnersList); - boolean consensusIDcheck = false; - if(dhtOwnersList.size() == 2 && dhtOwnersList.contains(senderPID) && dhtOwnersList.contains(receiverPID)) - consensusIDcheck = true; - - -// writeToFile(LOGGER_PATH + "tempverifysenderhash", verifySenderHash, false); -// String verifySenderIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "tempverifysenderhash", ipfs); -// deleteFile(LOGGER_PATH + "tempverifysenderhash"); - - if (Authenticate.verifySignature(detailsToVerify.toString()) && consensusIDcheck) { - QuorumConsensusLogger.debug("Quorum Authenticated Sender"); - String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", quorumHash); - out.println(QuorumSignature); - String creditval; - creditval = in.readLine(); - QuorumConsensusLogger.debug("credit value " + creditval); - - if (!creditval.equals("null")) { //commented as per test for multiple consensus threads - - FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); - shareWriter.write(creditval); - shareWriter.close(); - File readCredit = new File(LOGGER_PATH + "mycredit.txt"); - String credit = add(readCredit.toString(), ipfs); - - // adding credit to credit mapping - JSONArray CreditBody = new JSONArray(creditval); - JSONObject creditMappingObject = new JSONObject(); - JSONArray creditMappingArray = new JSONArray(); - - for(int i = 0; i < CreditBody.length(); i++){ - JSONObject object = CreditBody.getJSONObject(i); - String key = object.getString("did"); - String sign = object.getString("sign"); - String creditHash = calculateHash(sign, "SHA3-256"); - - creditMappingObject.put("did", key); - creditMappingObject.put("sign", sign); - creditMappingObject.put("hash", creditHash); - creditMappingObject.put("tid", transactionID); - - creditMappingArray.put(creditMappingObject); - - writeToFile(WALLET_DATA_PATH + "CreditMapping.json", creditMappingArray.toString(), false); + } else { + ValidationHandler.debug("Sender Authentication Failure - Quorum"); + out.println("Auth_Failed"); + } + } + if (readSenderData.getString(TRANS_TYPE) == PRIMARY) { + + receiverDID = readSenderData.getString("RID"); + String quorumHash = calculateHash(verifySenderHash.concat(receiverDID), "SHA3-256"); + + if (Authenticate.verifySignature(detailsToVerify.toString())) { + ValidationHandler.debug("Quorum Authenticated Sender"); + + ValidationHandler.debug("ConsensusID pass"); + String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + quorumHash); + out.println(QuorumSignature); + String creditval; + creditval = in.readLine(); + ValidationHandler.debug("credit value " + creditval); + + if (!creditval.equals("null")) { // commented as per test for multiple consensus threads + + FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); + shareWriter.write(creditval); + shareWriter.close(); + File readCredit = new File(LOGGER_PATH + "mycredit.txt"); + String credit = add(readCredit.toString(), ipfs); + pin(credit, ipfs); + // adding credit to credit mapping + JSONArray CreditBody = new JSONArray(creditval); + // JSONObject creditMappingObject = new JSONObject(); + JSONArray creditMappingArray = new JSONArray(); + + for (int i = 0; i < CreditBody.length(); i++) { + JSONObject creditMappingObject = new JSONObject(); + JSONObject object = CreditBody.getJSONObject(i); + String key = object.getString("did"); + String sign = object.getString("sign"); + String creditHash = calculateHash(sign, "SHA3-256"); + + creditMappingObject.put("did", key); + creditMappingObject.put("sign", sign); + creditMappingObject.put("hash", creditHash); + creditMappingObject.put("tid", transactionID); + + creditMappingArray.put(creditMappingObject); + + } + writeToFile(WALLET_DATA_PATH + "CreditMapping.json", creditMappingArray.toString(), + false); + + JSONObject storeDetailsQuorum = new JSONObject(); + storeDetailsQuorum.put("tid", transactionID); + storeDetailsQuorum.put("consensusID", verifySenderHash); + storeDetailsQuorum.put("sign", senderPrivatePos); + storeDetailsQuorum.put("credits", credit); + storeDetailsQuorum.put("senderdid", senderDidIpfsHash); + storeDetailsQuorum.put("recdid", receiverDID); + JSONArray data = new JSONArray(); + data.put(storeDetailsQuorum); + ValidationHandler.debug("Quorum Share: " + credit); + updateJSON("add", WALLET_DATA_PATH + "QuorumSignedTransactions.json", data.toString()); + deleteFile(LOGGER_PATH + "mycredit.txt"); + writeToFile(LOGGER_PATH + "consenusIDhash", verifySenderHash, false); + String consenusIDhash = IPFSNetwork.add(LOGGER_PATH + "consenusIDhash", ipfs); + deleteFile(LOGGER_PATH + "consenusIDhash"); + ValidationHandler.debug("added consensus ID " + consenusIDhash); + + } else { + JSONObject storeDetailsQuorum = new JSONObject(); + storeDetailsQuorum.put("tid", transactionID); + storeDetailsQuorum.put("consensusID", verifySenderHash); + storeDetailsQuorum.put("sign", senderPrivatePos); + storeDetailsQuorum.put("credits", ""); + storeDetailsQuorum.put("senderdid", senderDidIpfsHash); + storeDetailsQuorum.put("recdid", receiverDID); + JSONArray data = new JSONArray(); + data.put(storeDetailsQuorum); + updateJSON("add", WALLET_DATA_PATH + "QuorumSignedTransactions.json", data.toString()); } - JSONObject storeDetailsQuorum = new JSONObject(); - storeDetailsQuorum.put("tid", transactionID); - storeDetailsQuorum.put("consensusID", verifySenderHash); - storeDetailsQuorum.put("sign", senderPrivatePos); - storeDetailsQuorum.put("credits", credit); - storeDetailsQuorum.put("senderdid", senderDidIpfsHash); - storeDetailsQuorum.put("recdid", receiverDID); - JSONArray data = new JSONArray(); - data.put(storeDetailsQuorum); - QuorumConsensusLogger.debug("Quorum Share: " + credit); - updateJSON("add", WALLET_DATA_PATH + "QuorumSignedTransactions.json", data.toString()); - deleteFile(LOGGER_PATH + "mycredit.txt"); - writeToFile(LOGGER_PATH + "consenusIDhash", verifySenderHash, false); - String consenusIDhash = IPFSNetwork.add(LOGGER_PATH + "consenusIDhash", ipfs); - deleteFile(LOGGER_PATH + "consenusIDhash"); - QuorumConsensusLogger.debug("added consensus ID " + consenusIDhash); + + } else { + ValidationHandler.debug("Sender Authentication Failure - Quorum"); + out.println("Auth_Failed"); } - } else { - QuorumConsensusLogger.debug("Sender Authentication Failure - Quorum"); - out.println("Auth_Failed"); } } - } catch (IOException e) { - QuorumConsensusLogger.error("IOException Occurred", e); - } catch (JSONException e) { - QuorumConsensusLogger.error("JSONException Occurred", e); - } catch (NullPointerException | InterruptedException e) { - QuorumConsensusLogger.error("NullPointer Exception Occurred ",e); + } catch (Exception e) { + ValidationHandler.debug("Exception in Quorum Consensus: " + e); } - finally{ - try { - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } catch (IOException e) { - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - QuorumConsensusLogger.error("IOException Occurred", e); - } - - } } - } -} +} \ No newline at end of file diff --git a/src/com/rubix/Constants/ConsensusConstants.java b/src/com/rubix/Constants/ConsensusConstants.java index b67e588c..42c39c56 100644 --- a/src/com/rubix/Constants/ConsensusConstants.java +++ b/src/com/rubix/Constants/ConsensusConstants.java @@ -1,11 +1,15 @@ package com.rubix.Constants; - public class ConsensusConstants { public static final String TRANSACTION_ID = "Tid"; public static final String HASH = "Hash"; public static final String RECEIVERID = "RID"; - + public static final String TRANS_TYPE = "TRANASACTION_TYPE"; + public static final String TRANS_STATUS = "TRANSACTION_STATUS"; + public static final String TRANS_AMOUNT = "TRANSACTION_AMOUNT"; + public static final String PRIMARY = "PRIMARY_TOKENS"; + public static final String SECONDARY = "SECONDARY_TOKENS"; + public static final String DATA = "DATA_VALIDATION"; } diff --git a/src/com/rubix/Constants/IPFSConstants.java b/src/com/rubix/Constants/IPFSConstants.java index 32e442d7..10104954 100644 --- a/src/com/rubix/Constants/IPFSConstants.java +++ b/src/com/rubix/Constants/IPFSConstants.java @@ -9,12 +9,12 @@ public class IPFSConstants { public static String shutdown = "ipfs shutdown"; public static String daemon = "ipfs daemon"; - public static String repo ="ipfs repo gc"; - public static String unpin ="ipfs pin rm "; + public static String repo = "ipfs repo gc"; + public static String unpin = "ipfs pin rm "; public static String pin = "ipfs pin "; public static String bootstrap = "ipfs bootstrap "; - public static String add ="ipfs add "; - public static String hashOnly ="ipfs add --only-hash "; + public static String add = "ipfs add "; + public static String hashOnly = "ipfs add --only-hash "; public static String get = "ipfs get "; public static String swarmPeers = "ipfs swarm peers"; } diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 6563a971..b2b0af27 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -1,10 +1,24 @@ package com.rubix.Resources; -import com.rubix.TokenTransfer.ProofCredits; -import com.rubix.TokenTransfer.TokenSender; -import io.ipfs.api.*; -import org.apache.log4j.*; -import org.json.*; +import static com.rubix.Constants.ConsensusConstants.DATA; +import static com.rubix.Constants.ConsensusConstants.PRIMARY; +import static com.rubix.Constants.ConsensusConstants.TRANS_TYPE; +import static com.rubix.Resources.Functions.DATA_PATH; +import static com.rubix.Resources.Functions.IPFS_PORT; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.SEND_PORT; +import static com.rubix.Resources.Functions.SYNC_IP; +import static com.rubix.Resources.Functions.WALLET_DATA_PATH; +import static com.rubix.Resources.Functions.getOsName; +import static com.rubix.Resources.Functions.getPeerID; +import static com.rubix.Resources.Functions.getValues; +import static com.rubix.Resources.Functions.nodeData; +import static com.rubix.Resources.Functions.readFile; +import static com.rubix.Resources.Functions.writeToFile; +import static com.rubix.Resources.IPFSNetwork.add; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.pin; + import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -14,10 +28,24 @@ import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import com.rubix.TokenTransfer.ProofCredits; +import com.rubix.TokenTransfer.TokenSender; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import io.ipfs.api.IPFS; +import io.ipfs.api.Peer; public class APIHandler { private static final Logger APILogger = Logger.getLogger(APIHandler.class); @@ -26,77 +54,98 @@ public class APIHandler { /** * Initiates a transfer between two nodes + * * @param data Data specific to token transfer * @return Message from the sender with transaction details - * @throws JSONException handles JSON Exceptions + * @throws JSONException handles JSON Exceptions * @throws NoSuchAlgorithmException handles Invalid Algorithms Exceptions - * @throws IOException handles IO Exceptions + * @throws IOException handles IO Exceptions */ - - public static JSONObject send(String data) throws Exception { Functions.pathSet(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String senderPeerID = getPeerID(DATA_PATH + "DID.json"); String senDID = getValues(DATA_PATH + "DID.json", "didHash", "peerid", senderPeerID); - - - JSONObject dataObject = new JSONObject(data); - String recDID = dataObject.getString("receiverDidIpfsHash"); - + JSONObject sendMessage = new JSONObject(); String dataTableData = readFile(DATA_PATH + "DataTable.json"); boolean isObjectValid = false; JSONArray dataTable = new JSONArray(dataTableData); - // check value matches any of the data in the data table - for (int i = 0; i < dataTable.length(); i++) { - JSONObject dataTableObject = dataTable.getJSONObject(i); - if (dataTableObject.getString("didHash").equals(recDID)) { - isObjectValid = true; + String recDID; + String blockHash; + JSONArray tokens; + JSONObject dataObject = new JSONObject(data); + + if (dataObject.has("receiverDidIpfsHash")) { + + dataObject.put(TRANS_TYPE, PRIMARY); + + recDID = dataObject.getString("receiverDidIpfsHash"); + tokens = dataObject.getJSONArray("tokens"); + + if (tokens.length() < 1) { + sendMessage.put("did", senDID); + sendMessage.put("tid", "null"); + sendMessage.put("status", "Failed"); + sendMessage.put("message", "Invalid amount"); + return sendMessage; } - } - if(!isObjectValid) - networkInfo(); -// String comments = dataObject.getString("comments"); - JSONArray tokens = dataObject.getJSONArray("tokens"); -// JSONArray tokenHeader = dataObject.getJSONArray("tokenHeader"); -// int amount = dataObject.getInt("amount"); + if (recDID.length() != 46) { + sendMessage.put("did", senDID); + sendMessage.put("tid", "null"); + sendMessage.put("status", "Failed"); + sendMessage.put("message", "Invalid Receiver Did Entered"); + return sendMessage; + } + for (int i = 0; i < dataTable.length(); i++) { + JSONObject dataTableObject = dataTable.getJSONObject(i); + if (dataTableObject.getString("didHash").equals(recDID)) { + isObjectValid = true; + } + } + if (!isObjectValid) + networkInfo(); - JSONObject sendMessage = new JSONObject(); - if (recDID.length() != 46) { - sendMessage.put("did", senDID); - sendMessage.put("tid", "null"); - sendMessage.put("status", "Failed"); - sendMessage.put("message", "Invalid Receiver Did Entered"); - return sendMessage; - } + } else if (dataObject.has("blockHash")) { + + dataObject.put(TRANS_TYPE, DATA); - if (tokens.length() < 1) { + blockHash = dataObject.getString("blockHash"); + if (blockHash.length() != 46) { + sendMessage.put("did", senDID); + sendMessage.put("tid", "null"); + sendMessage.put("status", "Failed"); + sendMessage.put("message", "Invalid Block Hash Entered"); + return sendMessage; + } + + } else { sendMessage.put("did", senDID); sendMessage.put("tid", "null"); sendMessage.put("status", "Failed"); - sendMessage.put("message", "Invalid amount"); + sendMessage.put("message", "Invalid Data Entered"); return sendMessage; + } -// detailsObject.put("tokens", tokens); -// detailsObject.put("receiverDidIpfsHash", recDID); -// detailsObject.put("comment", comments); -// detailsObject.put("pvt", DATA_PATH + senDID + "/PrivateShare.png"); -// detailsObject.put("tokenHeader", tokenHeader); -// detailsObject.put("amount", amount); dataObject.put("pvt", DATA_PATH + senDID + "/PrivateShare.png"); - sendMessage = TokenSender.Send(dataObject.toString(), ipfs, SEND_PORT); + APILogger.info("Initiating transaction for:" + dataObject.toString()); + sendMessage = TokenSender.Send(dataObject.toString(), ipfs, SEND_PORT); -// sendMessage = TokenSender.Send(detailsObject.toString(), ipfs, SEND_PORT); APILogger.info(sendMessage); return sendMessage; } - + /** + * An API call to mine tokens + * + * @param type Type of quorum Selection + * @return JSONObject with status message + * @throws Exception throws Exception + */ public static JSONObject create(int type) throws Exception { Functions.pathSet(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -114,7 +163,7 @@ public static JSONObject create(int type) throws Exception { isObjectValid = true; } } - if(!isObjectValid) + if (!isObjectValid) networkInfo(); JSONObject sendMessage = new JSONObject(); @@ -122,14 +171,14 @@ public static JSONObject create(int type) throws Exception { detailsObject.put("receiverDidIpfsHash", senDID); detailsObject.put("pvt", DATA_PATH + senDID + "/PrivateShare.png"); detailsObject.put("type", type); - sendMessage = ProofCredits.create(detailsObject.toString(), ipfs); + sendMessage = ProofCredits.create(detailsObject.toString(), ipfs); APILogger.info(sendMessage); return sendMessage; } - /** * A call to get details of a transaction given its ID + * * @param txnId * @return Transaction Details * @throws JSONException handles JSON Exceptions @@ -138,7 +187,7 @@ public static JSONArray transactionDetails(String txnId) throws JSONException { String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONObject countResult = new JSONObject(); JSONArray resultArray = new JSONArray(); - if (transactionHistory.length() == 0){ + if (transactionHistory.length() == 0) { countResult.put("Message", "No transactions found"); resultArray.put(countResult); return resultArray; @@ -148,8 +197,11 @@ public static JSONArray transactionDetails(String txnId) throws JSONException { JSONObject obj = new JSONObject(); for (int i = 0; i < transArray.length(); i++) { obj = transArray.getJSONObject(i); - if (obj.get("txn").equals(txnId)) + if (obj.get("txn").equals(txnId)) { + obj.remove("essentialShare"); resultArray.put(obj); + } + } APILogger.info("Transaction Details for : " + obj.toString()); return resultArray; @@ -157,6 +209,7 @@ public static JSONArray transactionDetails(String txnId) throws JSONException { /** * A call to get the account information + * * @return Detailed explanation of the account information of the user * @throws JSONException handles JSON Exceptions */ @@ -176,12 +229,13 @@ public static JSONArray accountInformation() throws JSONException { String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); - if(!(transArray.length() == 0)){ + if (!(transArray.length() == 0)) { for (int i = 0; i < transArray.length(); i++) { objectParser = transArray.getJSONObject(i); if (objectParser.get("role").equals("Sender")) txnAsSender++; - else txnAsReceiver++; + else + txnAsReceiver++; } } @@ -197,8 +251,26 @@ public static JSONArray accountInformation() throws JSONException { return resultArray; } + /** + * A method to add and host your DID ans Public share to ipfs + */ + public static void addPublicData() { + String peerID = getPeerID(DATA_PATH + "DID.json"); + String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID); + String walletHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "peerid", peerID); + + add(DATA_PATH.concat(didHash).concat("/DID.png"), ipfs); + pin(didHash, ipfs); + + add(DATA_PATH.concat(didHash).concat("/PublicShare.png"), ipfs); + pin(walletHash, ipfs); + + APILogger.debug("Data Added and Pinned"); + } + /** * A call to sync all the nodes in the network + * * @return Message if failed or succeeded * @throws IOException */ @@ -232,6 +304,7 @@ public static String networkInfo() throws IOException, JSONException { /** * A call to get list transactions between two mentioned dates + * * @param s Start Date * @param e End Date * @return List of transactions @@ -239,17 +312,17 @@ public static String networkInfo() throws IOException, JSONException { */ public static JSONArray transactionsByDate(String s, String e) throws JSONException, ParseException { JSONArray resultArray = new JSONArray(); - String strDateFormat = "yyyy-MMM-dd HH:mm:ss"; //Date format is Specified + String strDateFormat = "yyyy-MMM-dd HH:mm:ss"; // Date format is Specified SimpleDateFormat objSDF = new SimpleDateFormat(strDateFormat); - Date date1=new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(s); - String startDateString= objSDF.format(date1); - Date date2=new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(e); - String endDateString= objSDF.format(date2); + Date date1 = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(s); + String startDateString = objSDF.format(date1); + Date date2 = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(e); + String endDateString = objSDF.format(date2); JSONObject countResult = new JSONObject(); Date startDate = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").parse(startDateString); Date endDate = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").parse(endDateString); - APILogger.debug("start date is "+startDate); - APILogger.debug("end date is "+endDate); + APILogger.debug("start date is " + startDate); + APILogger.debug("end date is " + endDate); File fileCheck1 = new File(WALLET_DATA_PATH + "TransactionHistory.json"); if (!fileCheck1.exists()) { countResult.put("Message", "File not found"); @@ -258,28 +331,31 @@ public static JSONArray transactionsByDate(String s, String e) throws JSONExcept } String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); - if (transArray.length() == 0){ + if (transArray.length() == 0) { countResult.put("Message", "No Transactions made yet"); resultArray.put(countResult); return resultArray; } - for (int i=0;i= transArray.length()) { - for (int i = transArray.length()-1; i>=0; i--) + for (int i = transArray.length() - 1; i >= 0; i--) { + transArray.getJSONObject(i).remove("essentialShare"); resultArray.put(transArray.get(i)); + } return resultArray; } - for( int i = 1; i <= n; i++) + for (int i = 1; i <= n; i++) { + transArray.getJSONObject(i).remove("essentialShare"); resultArray.put(transArray.getJSONObject(transArray.length() - i)); - + } return resultArray; } /** * A call to get list transactions within a range + * * @param start start index - * @param end end index + * @param end end index * @return List of transactions * @throws JSONException handles JSON Exceptions */ @@ -341,14 +421,14 @@ public static JSONArray transactionsByRange(int start, int end) throws JSONExcep String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); - if (transArray.length() == 0){ + if (transArray.length() == 0) { resultArray.put(countResult); return resultArray; } - - for(int i = start; i < end; i++){ + for (int i = start; i < end; i++) { JSONObject object = transArray.getJSONObject(i); + object.remove("essentialShare"); resultArray.put(object); } @@ -358,12 +438,13 @@ public static JSONArray transactionsByRange(int start, int end) throws JSONExcep /** * A call to close all open IPFS streams */ - public static void closeStreams(){ + public static void closeStreams() { executeIPFSCommands("ipfs p2p close --all"); } /** * A call to get list transactions with the mentioned comment + * * @param comment Comment * @return List of transactions * @throws JSONException handles JSON Exceptions @@ -376,10 +457,13 @@ public static JSONArray transactionsByComment(String comment) throws JSONExcepti JSONArray resultArray = new JSONArray(); for (int i = 0; i < transArray.length(); i++) { obj = transArray.getJSONObject(i); - if (obj.get("comment").equals(comment)) + if (obj.get("comment").equals(comment)) { + obj.remove("essentialShare"); resultArray.put(obj); + } + } - if(resultArray.length() < 1){ + if (resultArray.length() < 1) { JSONObject returnObject = new JSONObject(); returnObject.put("Message", "No transactions found with the comment " + comment); resultArray.put(returnObject); @@ -388,9 +472,9 @@ public static JSONArray transactionsByComment(String comment) throws JSONExcepti return resultArray; } - /** * A call to get list transactions made by the user with the input Did + * * @param did DID of the contact * @return List of transactions committed with the user DID * @throws JSONException handles JSON Exceptions @@ -401,33 +485,31 @@ public static JSONArray transactionsByDID(String did) throws JSONException { JSONArray resultArray = new JSONArray(); for (int i = 0; i < transArray.length(); i++) { JSONObject didObject = transArray.getJSONObject(i); + didObject.remove("essentialShare"); if (didObject.get("senderDID").equals(did) || didObject.get("receiverDID").equals(did)) - resultArray.put(didObject); + resultArray.put(didObject); } return resultArray; } - public static int onlinePeersCount() throws JSONException, IOException, InterruptedException { JSONArray peersArray = peersOnlineStatus(); int count = 0; - for (int i = 0; i < peersArray.length(); i++){ - if(peersArray.getJSONObject(i).getString("onlineStatus").contains("online")) + for (int i = 0; i < peersArray.length(); i++) { + if (peersArray.getJSONObject(i).getString("onlineStatus").contains("online")) count++; } return count; } - public static ArrayList swarmPeersList() throws IOException, InterruptedException { String OS = getOsName(); String[] command = new String[3]; - if(OS.contains("Mac") || OS.contains("Linux")){ + if (OS.contains("Mac") || OS.contains("Linux")) { command[0] = "bash"; command[1] = "-c"; - } - else if(OS.contains("Windows")){ + } else if (OS.contains("Windows")) { command[0] = "cmd.exe"; command[1] = "/c"; } @@ -438,7 +520,7 @@ else if(OS.contains("Windows")){ ArrayList peersArray = new ArrayList(); String line; - while((line = br.readLine()) != null) { + while ((line = br.readLine()) != null) { peersArray.add(line); } if (!OS.contains("Windows")) @@ -447,20 +529,22 @@ else if(OS.contains("Windows")){ P.destroy(); ArrayList peersIdentities = new ArrayList(); - if(peersArray.size() != 0){ + if (peersArray.size() != 0) { List k = ipfs.swarm.peers(); - for(int i = 0; i < k.size(); i++) + for (int i = 0; i < k.size(); i++) peersIdentities.add(k.get(i).toString().substring(0, 46)); return peersIdentities; } return peersArray; } + /** * A call to get the online/offline status of your contacts + * * @return List indicating online status of each DID contact * @throws JSONException handles JSON Exceptions - * @throws IOException handles IO Exceptions + * @throws IOException handles IO Exceptions */ public static JSONArray peersOnlineStatus() throws JSONException, IOException, InterruptedException { ArrayList peersArray = swarmPeersList(); @@ -468,16 +552,15 @@ public static JSONArray peersOnlineStatus() throws JSONException, IOException, I JSONArray dataArray = new JSONArray(dataTable); JSONArray onlinePeers = new JSONArray(); - for(int i = 0; i < dataArray.length(); i++){ + for (int i = 0; i < dataArray.length(); i++) { JSONObject peerObject = dataArray.getJSONObject(i); String peerID = peerObject.getString("peerid"); - if(peersArray.contains(peerID)){ + if (peersArray.contains(peerID)) { JSONObject onlinePeersObject = new JSONObject(); onlinePeersObject.put("did", getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID)); onlinePeersObject.put("onlineStatus", "online"); onlinePeers.put(onlinePeersObject); - } - else{ + } else { JSONObject onlinePeersObject = new JSONObject(); onlinePeersObject.put("did", getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID)); onlinePeersObject.put("onlineStatus", "offline"); @@ -491,6 +574,7 @@ public static JSONArray peersOnlineStatus() throws JSONException, IOException, I /** * A call to list out all contacts in the user wallet + * * @return A list of user wallet contacts * @throws JSONException handles JSON Exceptions */ @@ -498,7 +582,7 @@ public static JSONArray contacts() throws JSONException { String dataTable = readFile(DATA_PATH + "DataTable.json"); JSONArray dataArray = new JSONArray(dataTable); JSONArray didArray = new JSONArray(); - for (int i = 0; i < dataArray.length(); i++){ + for (int i = 0; i < dataArray.length(); i++) { didArray.put(dataArray.getJSONObject(i).getString("didHash")); } return didArray; @@ -506,6 +590,7 @@ public static JSONArray contacts() throws JSONException { /** * A call to list out number of transactions made per day + * * @return List of transactions committed on every date * @throws JSONException handles JSON Exceptions */ @@ -513,18 +598,18 @@ public static JSONArray txnPerDay() throws JSONException { String dataTable = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray dataArray = new JSONArray(dataTable); HashSet dateSet = new HashSet<>(); - for(int i = 0; i < dataArray.length(); i++) + for (int i = 0; i < dataArray.length(); i++) dateSet.add(dataArray.getJSONObject(i).getString("Date")); JSONObject datesTxn = new JSONObject(); Iterator dateIterator = dateSet.iterator(); - while (dateIterator.hasNext()){ + while (dateIterator.hasNext()) { String date = dateIterator.next(); int count = 0; - for(int i = 0; i < dataArray.length(); i++){ + for (int i = 0; i < dataArray.length(); i++) { JSONObject object = dataArray.getJSONObject(i); - if(date.equals(object.getString("Date"))){ + if (date.equals(object.getString("Date"))) { count++; } } @@ -540,7 +625,8 @@ public static JSONObject syncNetworkNodes() throws JSONException, IOException { JSONArray dataArray = new JSONArray(dataTable); for (int i = 0; i < dataArray.length(); i++) - nodeData(dataArray.getJSONObject(i).getString("didHash"), dataArray.getJSONObject(i).getString("walletHash"), ipfs); + nodeData(dataArray.getJSONObject(i).getString("didHash"), + dataArray.getJSONObject(i).getString("walletHash"), ipfs); return new JSONObject("{\"message\":\"Synced all nodes\"}"); } diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index b7331468..5ee0029f 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1,6 +1,5 @@ package com.rubix.Resources; -import static com.rubix.Resources.APIHandler.networkInfo; import static com.rubix.Resources.IPFSNetwork.checkSwarmConnect; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.forwardCheck; @@ -15,8 +14,6 @@ import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -41,7 +38,6 @@ import io.ipfs.api.IPFS; - public class Functions { public static boolean mutex = false; @@ -51,7 +47,8 @@ public class Functions { public static String LOGGER_PATH = ""; public static String WALLET_DATA_PATH = ""; public static String PAYMENTS_PATH = ""; - public static int RECEIVER_PORT, GOSSIP_SENDER, GOSSIP_RECEIVER, QUORUM_PORT, SENDER2Q1, SENDER2Q2, SENDER2Q3, SENDER2Q4, SENDER2Q5, SENDER2Q6, SENDER2Q7; + public static int RECEIVER_PORT, GOSSIP_SENDER, GOSSIP_RECEIVER, QUORUM_PORT, SENDER2Q1, SENDER2Q2, SENDER2Q3, + SENDER2Q4, SENDER2Q5, SENDER2Q6, SENDER2Q7; public static int QUORUM_COUNT; public static int SEND_PORT; public static int IPFS_PORT; @@ -121,23 +118,20 @@ public static void pathSet() { SYNC_IP = pathsArray.getJSONObject(2).getString("SYNC_IP"); EXPLORER_IP = pathsArray.getJSONObject(2).getString("EXPLORER_IP"); USERDID_IP = pathsArray.getJSONObject(2).getString("USERDID_IP"); - ADVISORY_IP=pathsArray.getJSONObject(2).getString("ADVISORY_IP"); + ADVISORY_IP = pathsArray.getJSONObject(2).getString("ADVISORY_IP"); CONSENSUS_STATUS = pathsArray.getJSONObject(3).getBoolean("CONSENSUS_STATUS"); QUORUM_COUNT = pathsArray.getJSONObject(3).getInt("QUORUM_COUNT"); QUORUM_MEMBERS = pathsArray.getJSONObject(4); - BOOTSTRAPS =pathsArray.getJSONArray(5); - + BOOTSTRAPS = pathsArray.getJSONArray(5); } catch (JSONException e) { e.printStackTrace(); } } - - //? public static void nodeData(String did, String wid, IPFS ipfs) throws IOException { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); File dataFolder = new File(DATA_PATH + did + "/"); @@ -177,7 +171,6 @@ public static void nodeData(String did, String wid, IPFS ipfs) throws IOExceptio } } - /** * This method gets the currently logged in username * @@ -212,16 +205,15 @@ public static String getSystemUser() { return lineID; } - /** - * This method calculates different types of hashes as mentioned in the passed parameters for the mentioned message + * This method calculates different types of hashes as mentioned in the passed + * parameters for the mentioned message * * @param message Input string to be hashed * @param algorithm Specification of the algorithm used for hashing * @return (String) hash */ - //? rubix-crypto public static String calculateHash(String message, String algorithm) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); MessageDigest digest = null; @@ -282,13 +274,13 @@ public static String bytesToHex(byte[] inputHash) { StringBuilder outputHexString = new StringBuilder(); for (byte b : inputHash) { String hex = Integer.toHexString(0xff & b); - if (hex.length() == 1) outputHexString.append('0'); + if (hex.length() == 1) + outputHexString.append('0'); outputHexString.append(hex); } return outputHexString.toString(); } - /** * This method returns the content of the file passed to it * @@ -310,14 +302,15 @@ public static String readFile(String filePath) { return fileContent.toString(); } - /** * This method writes the mentioned data into the file passed to it - * This also allows to take a decision on whether or not to append the data to the already existing content in the file + * This also allows to take a decision on whether or not to append the data to + * the already existing content in the file * * @param filePath Location of the file to be read and written into * @param data Data to be added - * @param appendStatus Decides whether or not to append the new data into the already existing data + * @param appendStatus Decides whether or not to append the new data into the + * already existing data */ public synchronized static void writeToFile(String filePath, String data, Boolean appendStatus) { @@ -358,7 +351,6 @@ public static String getSignFromShares(String filePath, String hash) throws IOEx return p1; } - /** * This function will sign on JSON data with private share * @@ -403,7 +395,6 @@ public static void listenThread(JSONObject connectObject) { } - /** * This function converts any integer to its binary form * @@ -490,7 +481,8 @@ public static void updateJSON(String operation, String filePath, String data) { } /** - * This method gets you a required data from a JSON file with a tag to be compared with + * This method gets you a required data from a JSON file with a tag to be + * compared with * * @param filePath Location of the JSON file * @param get Data to be fetched from the file @@ -527,7 +519,8 @@ public static String getOsName() { } /** - * This function calculates the minimum number of quorum peers required for consensus to work + * This function calculates the minimum number of quorum peers required for + * consensus to work * * @return Minimum number of quorum count for consensus to work */ @@ -536,7 +529,8 @@ public static int minQuorum() { } /** - * This function calculates the minimum number of quorum peers required for consensus to work + * This function calculates the minimum number of quorum peers required for + * consensus to work * * @return Minimum number of quorum count for consensus to work */ @@ -544,7 +538,6 @@ public static int minQuorum(int count) { return (((count - 1) / 3) * 2) + 1; } - /** * This method checks if Quorum is available for consensus * @@ -555,13 +548,14 @@ public static ArrayList QuorumCheck(JSONArray quorum, int size) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); ArrayList peers = new ArrayList<>(); - if (quorum.length()>=minQuorum(size)) { + if (quorum.length() >= minQuorum(size)) { for (int i = 0; i < quorum.length(); i++) { String quorumPeer; try { quorumPeer = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", quorum.getString(i)); if (checkSwarmConnect().contains(quorumPeer)) { peers.add(quorumPeer); + FunctionsLogger.debug(quorumPeer + " added to list"); } } catch (JSONException e) { FunctionsLogger.error("JSON Exception Occurred", e); @@ -569,8 +563,8 @@ public static ArrayList QuorumCheck(JSONArray quorum, int size) { } } - FunctionsLogger.debug("Quorum Peer IDs : " + peers); - return peers; + FunctionsLogger.debug("Quorum Peer IDs : " + peers); + return peers; } else return null; } @@ -579,30 +573,27 @@ public static ArrayList QuorumCheck(JSONArray quorum, int size) { * This method is to connect to quorum nodes for consensus * * @param quorum JSONArray is list of quorum nodes didHash - * @param ipfs ipfs instance + * @param ipfs ipfs instance */ - public static void QuorumSwarmConnect(JSONArray quorum, IPFS ipfs) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - for (int i = 0; i < quorum.length(); i++) { - String quorumPeer; - try { - quorumPeer = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", quorum.getString(i)); + for (int i = 0; i < quorum.length(); i++) { + String quorumPeer; + try { + quorumPeer = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", quorum.getString(i)); - IPFSNetwork.swarmConnectP2P(quorumPeer,ipfs); + IPFSNetwork.swarmConnectP2P(quorumPeer, ipfs); - } catch (JSONException e) { - FunctionsLogger.error("JSON Exception Occurred", e); - e.printStackTrace(); - } + } catch (JSONException e) { + FunctionsLogger.error("JSON Exception Occurred", e); + e.printStackTrace(); } + } } - - /** * This method identifies the Peer ID of the system by IPFS during installation * @@ -610,7 +601,6 @@ public static void QuorumSwarmConnect(JSONArray quorum, IPFS ipfs) { * @return Your system's Peer ID assigned by IPFS */ - public static String getPeerID(String filePath) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); JSONArray fileContentArray; @@ -628,8 +618,6 @@ public static String getPeerID(String filePath) { return peerid; } - - public static int[] getPrivatePosition(int[] positions, int[] privateArray) { int[] PrivatePosition = new int[positions.length]; for (int k = 0; k < positions.length; k++) { @@ -640,7 +628,8 @@ public static int[] getPrivatePosition(int[] positions, int[] privateArray) { return PrivatePosition; } - public static JSONObject randomPositions(String role, String hash, int numberOfPositions, int[] pvt1) throws JSONException { + public static JSONObject randomPositions(String role, String hash, int numberOfPositions, int[] pvt1) + throws JSONException { int u = 0, l = 0, m = 0; int[] hashCharacters = new int[256]; @@ -697,18 +686,19 @@ public static JSONObject randomPositions(String role, String hash, int numberOfP * @param positionsCount Number of positions required * @return Extended array of positions */ -// public static int[] finalPositions(int[] randomPositions, int positionsCount) { -// int[] finalPositions = new int[positionsCount * 64]; -// int u = 0; -// for (int k = 0; k < positionsCount; k++) { -// for (int p = 0; p < 64; p++) { -// finalPositions[u] = randomPositions[k]; -// randomPositions[k]++; -// u++; -// } -// } -// return finalPositions; -// } + // public static int[] finalPositions(int[] randomPositions, int positionsCount) + // { + // int[] finalPositions = new int[positionsCount * 64]; + // int u = 0; + // for (int k = 0; k < positionsCount; k++) { + // for (int p = 0; p < 64; p++) { + // finalPositions[u] = randomPositions[k]; + // randomPositions[k]++; + // u++; + // } + // } + // return finalPositions; + // } /** * This function deletes the mentioned file @@ -726,69 +716,50 @@ public static void deleteFile(String fileName) { } - -// /** -// * This functions picks the required number of quorum members from the mentioned file -// * -// * @param filePath Location of the file -// * @param hash Data from which positions are chosen -// * @return List of chosen members from the file -// */ -// public static ArrayList quorumChooser(String filePath, String hash) { -// PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); -// ArrayList quorumList = new ArrayList(); -// try { -// String fileContent = readFile(filePath); -// JSONArray blockHeight = new JSONArray(fileContent); -// -// int[] hashCharacters = new int[256]; -// var randomPositions = new ArrayList(); -// HashSet positionSet = new HashSet<>(); -// for (int k = 0; positionSet.size() != 7; k++) { -// hashCharacters[k] = Character.getNumericValue(hash.charAt(k)); -// randomPositions.add((((2402 + hashCharacters[k]) * 2709) + ((k + 2709) + hashCharacters[(k)])) % blockHeight.length()); -// positionSet.add(randomPositions.get(k)); -// } -// -// for (Integer integer : positionSet) -// quorumList.add(blockHeight.getJSONObject(integer).getString("peer-id")); -// } catch (JSONException e) { -// FunctionsLogger.error("JSON Exception Occurred", e); -// e.printStackTrace(); -// } -// return quorumList; -// } + // /** + // * This functions picks the required number of quorum members from the + // mentioned file + // * + // * @param filePath Location of the file + // * @param hash Data from which positions are chosen + // * @return List of chosen members from the file + // */ + // public static ArrayList quorumChooser(String filePath, String hash) { + // PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + // ArrayList quorumList = new ArrayList(); + // try { + // String fileContent = readFile(filePath); + // JSONArray blockHeight = new JSONArray(fileContent); + // + // int[] hashCharacters = new int[256]; + // var randomPositions = new ArrayList(); + // HashSet positionSet = new HashSet<>(); + // for (int k = 0; positionSet.size() != 7; k++) { + // hashCharacters[k] = Character.getNumericValue(hash.charAt(k)); + // randomPositions.add((((2402 + hashCharacters[k]) * 2709) + ((k + 2709) + + // hashCharacters[(k)])) % blockHeight.length()); + // positionSet.add(randomPositions.get(k)); + // } + // + // for (Integer integer : positionSet) + // quorumList.add(blockHeight.getJSONObject(integer).getString("peer-id")); + // } catch (JSONException e) { + // FunctionsLogger.error("JSON Exception Occurred", e); + // e.printStackTrace(); + // } + // return quorumList; + // } /** - * This function is to be initially called to setup the environment of your project + * This function is to be initially called to setup the environment of your + * project */ public static void launch() { pathSet(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - int syncFlag = 0; - try { - executeIPFSCommands("ipfs daemon --enable-gc"); - if (!SYNC_IP.contains("127.0.0.1")) { - networkInfo(); - syncFlag = 1; - } + executeIPFSCommands("ipfs daemon --enable-gc"); - } catch (MalformedURLException e) { - FunctionsLogger.error("MalformedURL Exception Occurred", e); - e.printStackTrace(); - } catch (ProtocolException e) { - FunctionsLogger.error("Protocol Exception Occurred", e); - e.printStackTrace(); - } catch (IOException e) { - FunctionsLogger.error("IO Exception Occurred", e); - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); - } - if (syncFlag == 1) - FunctionsLogger.info("Synced Successfully!"); - else - FunctionsLogger.info("Not synced! Try again after sometime."); + FunctionsLogger.debug("Enabled ipfs GC"); } /** @@ -797,7 +768,6 @@ public static void launch() { * @return A message * @throws JSONException handle all JSON Exceptions */ - //? self-test public static String checkDirectory() throws JSONException { setDir(); File mainDir = new File(dirPath); @@ -828,7 +798,8 @@ public static String checkDirectory() throws JSONException { File tokenChainsFolder = new File(TOKENCHAIN_PATH); File walletDataFolder = new File(WALLET_DATA_PATH); - if (!dataFolder.exists() || !loggerFolder.exists() || !tokenChainsFolder.exists() || !tokensFolder.exists() || !walletDataFolder.exists()) { + if (!dataFolder.exists() || !loggerFolder.exists() || !tokenChainsFolder.exists() || !tokensFolder.exists() + || !walletDataFolder.exists()) { dataFolder.delete(); loggerFolder.delete(); tokenChainsFolder.delete(); @@ -890,8 +861,8 @@ public static String checkDirectory() throws JSONException { * This method is used generate new token given level and tokenNumber * New token is the multi hash of hash of token number and hex of level * - * @param level level in token tree - * @param tokenNumber unique number for particular level in token tree + * @param level level in token tree + * @param tokenNumber unique number for particular level in token tree * @return mined token */ @@ -899,13 +870,12 @@ public static String mineToken(int level, int tokenNumber) { String tokenHash = calculateHash(String.valueOf(tokenNumber), "SHA-256"); String levelHex = Integer.toHexString(level); - if(level<16) - levelHex=String.valueOf(0).concat(levelHex); + if (level < 16) + levelHex = String.valueOf(0).concat(levelHex); String token = String.valueOf(0) + levelHex + tokenHash; return token; } - public static String toBinary(int x, int len) { if (len > 0) { return String.format("%" + len + "s", @@ -921,15 +891,14 @@ public static String toBinary(int x, int len) { * @return true if data is unique , false otherwise */ - public static Boolean integrityCheck(String consensusID){ - File file = new File(WALLET_DATA_PATH+"QuorumSignedTransactions.json"); - if(file.exists()) { + public static Boolean integrityCheck(String consensusID) { + File file = new File(WALLET_DATA_PATH + "QuorumSignedTransactions.json"); + if (file.exists()) { if (getValues(file.getAbsolutePath(), "senderdid", "consensusID", consensusID).equals("")) return true; else return false; - } - else + } else return true; } @@ -940,25 +909,24 @@ public static Boolean integrityCheck(String consensusID){ public static Date getCurrentUtcTime() throws ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); - return localDateFormat.parse( simpleDateFormat.format(new Date()) ); + return localDateFormat.parse(simpleDateFormat.format(new Date())); } - /** * This method is used to update quorum credits in server * - * @param quorumArray jsonarray of all quorum - * @param signedQuorumList jsonarray of all signedquorum - * @param status boolean for consensus status - * @param type transaction type : default to 1 + * @param quorumArray jsonarray of all quorum + * @param signedQuorumList jsonarray of all signedquorum + * @param status boolean for consensus status + * @param type transaction type : default to 1 * @return mined token */ + public static void updateQuorum(JSONArray quorumArray, JSONArray signedQuorumList, boolean status, int type) + throws IOException, JSONException { - public static void updateQuorum(JSONArray quorumArray,JSONArray signedQuorumList,boolean status,int type) throws IOException, JSONException { - - if (type==1) { - String urlQuorumUpdate = ADVISORY_IP+"/updateQuorum"; + if (type == 1) { + String urlQuorumUpdate = ADVISORY_IP + "/updateQuorum"; URL objQuorumUpdate = new URL(urlQuorumUpdate); HttpURLConnection conQuorumUpdate = (HttpURLConnection) objQuorumUpdate.openConnection(); @@ -970,8 +938,8 @@ public static void updateQuorum(JSONArray quorumArray,JSONArray signedQuorumList JSONObject dataToSendQuorumUpdate = new JSONObject(); dataToSendQuorumUpdate.put("completequorum", quorumArray); - dataToSendQuorumUpdate.put("signedquorum",signedQuorumList); - dataToSendQuorumUpdate.put("status",status); + dataToSendQuorumUpdate.put("signedquorum", signedQuorumList); + dataToSendQuorumUpdate.put("status", status); String populateQuorumUpdate = dataToSendQuorumUpdate.toString(); conQuorumUpdate.setDoOutput(true); @@ -997,22 +965,21 @@ public static void updateQuorum(JSONArray quorumArray,JSONArray signedQuorumList } } - /** * This method is used get getquorum from advisory node * - * @param betaHash betahash in string form - * @param gammaHash gammahash in string form - * @param senderDidIpfsHash didhash of sender + * @param betaHash betahash in string form + * @param gammaHash gammahash in string form + * @param senderDidIpfsHash didhash of sender * @param receiverDidIpfsHash didhash of receiver - * @param tokenslength tokens amount for picking quorum + * @param tokenslength tokens amount for picking quorum * @return JSONArray of quorum nodes */ - - public static JSONArray getQuorum(String betaHash,String gammaHash,String senderDidIpfsHash,String receiverDidIpfsHash,int tokenslength) throws IOException, JSONException { + public static JSONArray getQuorum(String betaHash, String gammaHash, String senderDidIpfsHash, + String receiverDidIpfsHash, int tokenslength) throws IOException, JSONException { JSONArray quorumArray; - String urlQuorumPick = ADVISORY_IP+"/getQuorum"; + String urlQuorumPick = ADVISORY_IP + "/getQuorum"; URL objQuorumPick = new URL(urlQuorumPick); HttpURLConnection conQuorumPick = (HttpURLConnection) objQuorumPick.openConnection(); @@ -1027,7 +994,7 @@ public static JSONArray getQuorum(String betaHash,String gammaHash,String sender dataToSendQuorumPick.put("gammahash", gammaHash); dataToSendQuorumPick.put("sender", senderDidIpfsHash); dataToSendQuorumPick.put("receiver", receiverDidIpfsHash); - dataToSendQuorumPick.put("tokencount",tokenslength); + dataToSendQuorumPick.put("tokencount", tokenslength); String populateQuorumPick = dataToSendQuorumPick.toString(); conQuorumPick.setDoOutput(true); @@ -1049,7 +1016,7 @@ public static JSONArray getQuorum(String betaHash,String gammaHash,String sender responseQuorumPick.append(outputQuorumPick); } inQuorumPick.close(); - + FunctionsLogger.debug(" responsequorumpick " + responseQuorumPick.toString()); quorumArray = new JSONArray(responseQuorumPick.toString()); return quorumArray; } @@ -1062,8 +1029,8 @@ public static JSONArray getQuorum(String betaHash,String gammaHash,String sender * @return JSONArray of quorum nodes */ - public static void mineUpdate(String didHash,int credits) throws IOException, JSONException { - String urlMineUpdate = ADVISORY_IP+"/updatemine"; + public static void mineUpdate(String didHash, int credits) throws IOException, JSONException { + String urlMineUpdate = ADVISORY_IP + "/updatemine"; URL objMineUpdate = new URL(urlMineUpdate); HttpURLConnection conMineUpdate = (HttpURLConnection) objMineUpdate.openConnection(); @@ -1075,7 +1042,7 @@ public static void mineUpdate(String didHash,int credits) throws IOException, JS JSONObject dataToSendMineUpdate = new JSONObject(); dataToSendMineUpdate.put("didhash", didHash); - dataToSendMineUpdate.put("credits",credits); + dataToSendMineUpdate.put("credits", credits); String populateMineUpdate = dataToSendMineUpdate.toString(); conMineUpdate.setDoOutput(true); @@ -1100,9 +1067,9 @@ public static void mineUpdate(String didHash,int credits) throws IOException, JS } - public static int checkHeartBeat(String peerId,String appName) { + public static int checkHeartBeat(String peerId, String appName) { - if(forwardCheck(appName, QUORUM_PORT , peerId)) { + if (forwardCheck(appName, QUORUM_PORT, peerId)) { IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + peerId); return 1; } @@ -1112,42 +1079,67 @@ public static int checkHeartBeat(String peerId,String appName) { return 0; } } - -// /** -// * This method checks if Quorum is available for consensus -// * -// * @param quorum List of peers -// * @param ipfs IPFS instance -// * @return final list of all available Quorum peers -// */ -// public static ArrayList checkQuorum(JSONArray quorum, IPFS ipfs,int size) { -// PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); -// ArrayList peers = new ArrayList<>(); -// -// if (quorum.length()>=minQuorum(size)) { -// /**Swarm connect - sticky connection */ -// QuorumSwarmConnect(quorum, ipfs); -// for (int i = 0; i < quorum.length(); i++) { -// String quorumPeer; -// try { -// quorumPeer = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", quorum.getString(i)); -// if (checkSwarmConnect().contains(quorumPeer)) { -// peers.add(quorumPeer); -// FunctionsLogger.debug(quorumPeer); -// }else { -// FunctionsLogger.debug("cannot connect to Peer : " + quorumPeer); -// } -// } catch (JSONException e) { -// FunctionsLogger.error("JSON Exception Occurred", e); -// e.printStackTrace(); -// } -// } -// -// FunctionsLogger.debug("Quorum Peer IDs : " + peers); -// return peers; -// } else -// return null; -// } -} + /** To Sync DataTable.json, if required */ + public static void syncDataTable(String did, String peerId) { + try { + String dataTableData = readFile(DATA_PATH + "DataTable.json"); + boolean isObjectValid = false; + JSONArray dataTable = new JSONArray(dataTableData); + for (int i = 0; i < dataTable.length(); i++) { + JSONObject dataTableObject = dataTable.getJSONObject(i); + if ((did != null && dataTableObject.getString("didHash").equals(did)) + || + (peerId != null && dataTableObject.getString("peerid").equals(peerId))) { + isObjectValid = true; + break; + } + } + if (!isObjectValid) { + FunctionsLogger.debug("Syncing Datatable.json!"); + APIHandler.networkInfo(); + } + } catch (Exception e) { + FunctionsLogger.error("Exception Occured", e); + e.printStackTrace(); + } + } + // /** + // * This method checks if Quorum is available for consensus + // * + // * @param quorum List of peers + // * @param ipfs IPFS instance + // * @return final list of all available Quorum peers + // */ + // public static ArrayList checkQuorum(JSONArray quorum, IPFS ipfs,int + // size) { + // PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + // ArrayList peers = new ArrayList<>(); + // + // if (quorum.length()>=minQuorum(size)) { + // /**Swarm connect - sticky connection */ + // QuorumSwarmConnect(quorum, ipfs); + // for (int i = 0; i < quorum.length(); i++) { + // String quorumPeer; + // try { + // quorumPeer = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", + // quorum.getString(i)); + // if (checkSwarmConnect().contains(quorumPeer)) { + // peers.add(quorumPeer); + // FunctionsLogger.debug(quorumPeer); + // }else { + // FunctionsLogger.debug("cannot connect to Peer : " + quorumPeer); + // } + // } catch (JSONException e) { + // FunctionsLogger.error("JSON Exception Occurred", e); + // e.printStackTrace(); + // } + // } + // + // FunctionsLogger.debug("Quorum Peer IDs : " + peers); + // return peers; + // } else + // return null; + // } +} diff --git a/src/com/rubix/Resources/IPFSNetwork.java b/src/com/rubix/Resources/IPFSNetwork.java index 72c894ea..db8f1a2d 100644 --- a/src/com/rubix/Resources/IPFSNetwork.java +++ b/src/com/rubix/Resources/IPFSNetwork.java @@ -1,22 +1,35 @@ package com.rubix.Resources; -import io.ipfs.api.IPFS; -import io.ipfs.api.MerkleNode; -import io.ipfs.api.NamedStreamable; -import io.ipfs.multiaddr.MultiAddress; -import io.ipfs.multihash.Multihash; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.json.JSONException; +import static com.rubix.Constants.IPFSConstants.bootstrap; +import static com.rubix.Constants.IPFSConstants.daemon; +import static com.rubix.Constants.IPFSConstants.forward; +import static com.rubix.Constants.IPFSConstants.listen; +import static com.rubix.Constants.IPFSConstants.p2p; +import static com.rubix.Constants.IPFSConstants.shutdown; +import static com.rubix.Resources.Functions.BOOTSTRAPS; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.getOsName; -import javax.imageio.ImageIO; import java.awt.image.BufferedImage; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; -import static com.rubix.Constants.IPFSConstants.*; -import static com.rubix.Resources.Functions.*; +import javax.imageio.ImageIO; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONException; + +import io.ipfs.api.IPFS; +import io.ipfs.api.MerkleNode; +import io.ipfs.api.NamedStreamable; +import io.ipfs.multiaddr.MultiAddress; +import io.ipfs.multihash.Multihash; public class IPFSNetwork { public static int swarmAttempt = 0; @@ -69,105 +82,109 @@ public static String checkSwarmConnect() { return response; } -// public static void swarmConnector(String peerid, IPFS ipfs) throws JSONException { -// PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); -// String bootNode; -// int j; -// -// try { -// if (!checkSwarmConnect().contains(peerid)) { -// Random ran = new Random(); -// -// List bootStrapList = ipfs.bootstrap.list(); -// Collections.shuffle(bootStrapList); -// ran.setSeed(123456); -// int bootstrapSize = bootStrapList.size(); -// -// j = ran.nextInt(bootstrapSize); -// bootNode = String.valueOf(bootStrapList.get(j)); -// bootNode = bootNode.substring(bootNode.length() - 46); -// IPFSNetworkLogger.debug(bootNode); -// while (!checkSwarmConnect().contains(bootNode)) { -// j = (j + 1) % bootstrapSize; -// bootNode = String.valueOf(bootStrapList.get(j)); -// bootNode = bootNode.substring(bootNode.length() - 46); -// IPFSNetworkLogger.debug("trying to connect: " + bootNode); -// } -// MultiAddress multiAddress = new MultiAddress("/p2p/" + bootNode + "/p2p-circuit/p2p/" + peerid); -// String output = swarmConnectProcess(multiAddress); -// if (!output.contains("success")) -// swarmConnect(peerid); -// else -// IPFSNetworkLogger.debug("Connected via bootstrap node: " + bootNode); -// } else { -// IPFSNetworkLogger.debug("Connecting to Receiver directly"); -// -// } -// } catch (IOException e) { -// IPFSNetworkLogger.error("IOException Occurred", e); -// e.printStackTrace(); -// } -// -// } - -// /** -// * This method opens a new direct connection to a peer address. The address -// * format is an IPFS multiaddr. See -// * ipfs -// * swarm connect for more -// * -// * @param peerid is the multiaddr of the node -// */ -// -// public static void swarmConnect(String peerid) throws JSONException { -// PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); -// String bootNode; -// int j; -// -// IPFSNetworkLogger.debug("at swarmconnect " + peerid); -// if (!checkSwarmConnect().contains(peerid)) { -// Random ran = new Random(); -// -//// List bootStrapList = ipfs.bootstrap.list(); -//// Collections.shuffle(bootStrapList); -// ran.setSeed(123456); -// int bootstrapSize = BOOTSTRAPS.length(); -// -// IPFSNetworkLogger.debug("Bootstraps " + BOOTSTRAPS + "size " + bootstrapSize); -// -// j = ran.nextInt(bootstrapSize); -// bootNode = String.valueOf(BOOTSTRAPS.get(j)); -// bootNode = bootNode.substring(bootNode.length() - 46); -// IPFSNetworkLogger.debug("bootnode is " + bootNode); -// IPFSNetworkLogger.debug(bootNode); -// while (!checkSwarmConnect().contains(bootNode)) { -// j = (j + 1) % bootstrapSize; -// bootNode = String.valueOf(BOOTSTRAPS.get(j)); -// bootNode = bootNode.substring(bootNode.length() - 46); -// IPFSNetworkLogger.debug("trying to connect: " + bootNode); -// } -// MultiAddress multiAddress = new MultiAddress("/ipfs/" + bootNode + "/p2p-circuit/ipfs/" + peerid); -// String output = swarmConnectProcess(multiAddress); -// if (!output.contains("success")) { -// if (swarmAttempt < 25) { -// IPFSNetworkLogger.debug("swarm attempt round " + swarmAttempt); -// swarmAttempt++; -// swarmConnect(peerid); -// } else { -// IPFSNetworkLogger.debug("swarm attempt failed"); -// swarmAttempt = 0; -// } -// } else { -// IPFSNetworkLogger.debug("Connected via bootstrap node: " + bootNode); -// swarmAttempt = 0; -// } -// } else { -// IPFSNetworkLogger.debug("Connecting to Receiver directly"); -// swarmAttempt = 0; -// -// } -// -// } + // public static void swarmConnector(String peerid, IPFS ipfs) throws + // JSONException { + // PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + // String bootNode; + // int j; + // + // try { + // if (!checkSwarmConnect().contains(peerid)) { + // Random ran = new Random(); + // + // List bootStrapList = ipfs.bootstrap.list(); + // Collections.shuffle(bootStrapList); + // ran.setSeed(123456); + // int bootstrapSize = bootStrapList.size(); + // + // j = ran.nextInt(bootstrapSize); + // bootNode = String.valueOf(bootStrapList.get(j)); + // bootNode = bootNode.substring(bootNode.length() - 46); + // IPFSNetworkLogger.debug(bootNode); + // while (!checkSwarmConnect().contains(bootNode)) { + // j = (j + 1) % bootstrapSize; + // bootNode = String.valueOf(bootStrapList.get(j)); + // bootNode = bootNode.substring(bootNode.length() - 46); + // IPFSNetworkLogger.debug("trying to connect: " + bootNode); + // } + // MultiAddress multiAddress = new MultiAddress("/p2p/" + bootNode + + // "/p2p-circuit/p2p/" + peerid); + // String output = swarmConnectProcess(multiAddress); + // if (!output.contains("success")) + // swarmConnect(peerid); + // else + // IPFSNetworkLogger.debug("Connected via bootstrap node: " + bootNode); + // } else { + // IPFSNetworkLogger.debug("Connecting to Receiver directly"); + // + // } + // } catch (IOException e) { + // IPFSNetworkLogger.error("IOException Occurred", e); + // e.printStackTrace(); + // } + // + // } + + // /** + // * This method opens a new direct connection to a peer address. The address + // * format is an IPFS multiaddr. See + // * ipfs + // * swarm connect for more + // * + // * @param peerid is the multiaddr of the node + // */ + // + // public static void swarmConnect(String peerid) throws JSONException { + // PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + // String bootNode; + // int j; + // + // IPFSNetworkLogger.debug("at swarmconnect " + peerid); + // if (!checkSwarmConnect().contains(peerid)) { + // Random ran = new Random(); + // + //// List bootStrapList = ipfs.bootstrap.list(); + //// Collections.shuffle(bootStrapList); + // ran.setSeed(123456); + // int bootstrapSize = BOOTSTRAPS.length(); + // + // IPFSNetworkLogger.debug("Bootstraps " + BOOTSTRAPS + "size " + + // bootstrapSize); + // + // j = ran.nextInt(bootstrapSize); + // bootNode = String.valueOf(BOOTSTRAPS.get(j)); + // bootNode = bootNode.substring(bootNode.length() - 46); + // IPFSNetworkLogger.debug("bootnode is " + bootNode); + // IPFSNetworkLogger.debug(bootNode); + // while (!checkSwarmConnect().contains(bootNode)) { + // j = (j + 1) % bootstrapSize; + // bootNode = String.valueOf(BOOTSTRAPS.get(j)); + // bootNode = bootNode.substring(bootNode.length() - 46); + // IPFSNetworkLogger.debug("trying to connect: " + bootNode); + // } + // MultiAddress multiAddress = new MultiAddress("/ipfs/" + bootNode + + // "/p2p-circuit/ipfs/" + peerid); + // String output = swarmConnectProcess(multiAddress); + // if (!output.contains("success")) { + // if (swarmAttempt < 25) { + // IPFSNetworkLogger.debug("swarm attempt round " + swarmAttempt); + // swarmAttempt++; + // swarmConnect(peerid); + // } else { + // IPFSNetworkLogger.debug("swarm attempt failed"); + // swarmAttempt = 0; + // } + // } else { + // IPFSNetworkLogger.debug("Connected via bootstrap node: " + bootNode); + // swarmAttempt = 0; + // } + // } else { + // IPFSNetworkLogger.debug("Connecting to Receiver directly"); + // swarmAttempt = 0; + // + // } + // + // } /** * This function connects the peer node through the private swarm @@ -330,8 +347,8 @@ public static boolean dhtFindProvs(String MultiHash, String previousOwner, IPFS PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); Multihash dhtMultihash = Multihash.fromBase58(MultiHash); List dhtlist = ipfs.dht.findprovs(dhtMultihash); - - if (dhtlist.size() == 1 && dhtlist.toString().contains(previousOwner)) + IPFSNetworkLogger.debug("Providers: " + dhtlist); + if (dhtlist.size() <= 2 && dhtlist.toString().contains(previousOwner)) return true; return false; } @@ -366,7 +383,6 @@ public static ArrayList dhtOwnerCheck(String objectHash) throws InterruptedExcep commands[2] = "ipfs dht findprovs " + objectHash; } - ProcessBuilder p = new ProcessBuilder(commands); Process process = p.start(); @@ -379,7 +395,6 @@ public static ArrayList dhtOwnerCheck(String objectHash) throws InterruptedExcep array.add(line); process.waitFor(); - return array; } @@ -453,7 +468,8 @@ public static String executeIPFSCommandsResponse(String command) { } if (command.contains(listen) || command.contains(forward) || command.contains("swarm") - || command.contains(p2p) || command.contains(shutdown)) { + || command.contains(p2p) || command.contains(shutdown) || command.contains(bootstrap) + || command.contains("findprovs")) { p = new ProcessBuilder(commands); process = p.start(); @@ -520,7 +536,7 @@ public static void executeIPFSCommands(String command) { } if (command.contains(listen) || command.contains(forward) || command.contains(p2p) - || command.contains(shutdown)) { + || command.contains(shutdown) || command.contains(bootstrap)) { p = new ProcessBuilder(commands); process = p.start(); @@ -554,18 +570,28 @@ public static void swarmConnectP2P(String peerid, IPFS ipfs) throws JSONExceptio String output = swarmConnectProcess(multiAddress); if (!output.contains("success")) { + IPFSNetworkLogger.debug("Connecting via bootstrap "); + IPFSNetworkLogger.debug("Bootstraps " + BOOTSTRAPS + "size " + BOOTSTRAPS.length()); for (int i = 0; i < BOOTSTRAPS.length(); i++) { if (!swarmConnected) { bootNode = String.valueOf(BOOTSTRAPS.get(i)); bootNode = bootNode.substring(bootNode.length() - 46); - multiAddress = new MultiAddress("/ipfs/" + bootNode + "/p2p-circuit/ipfs/" + peerid); + multiAddress = new MultiAddress("/ipfs/" + bootNode); output = swarmConnectProcess(multiAddress); - if (!output.contains("success")) { - IPFSNetworkLogger.debug("swarm attempt failed with " + peerid); + + if (output.contains("success")) { + multiAddress = new MultiAddress("/ipfs/" + bootNode + "/p2p-circuit/ipfs/" + peerid); + output = swarmConnectProcess(multiAddress); + if (!output.contains("success")) { + IPFSNetworkLogger.debug("swarm attempt failed with " + peerid); + } else { + IPFSNetworkLogger.debug("swarm Connected : " + peerid); + swarmConnected = true; + } } else { - swarmConnected = true; + IPFSNetworkLogger.debug("bootstrap connection failed! " + bootNode); } } diff --git a/src/com/rubix/Resources/IntegrityCheck.java b/src/com/rubix/Resources/IntegrityCheck.java index d83d8c1f..33917e81 100644 --- a/src/com/rubix/Resources/IntegrityCheck.java +++ b/src/com/rubix/Resources/IntegrityCheck.java @@ -7,16 +7,14 @@ public class IntegrityCheck { public static String message; - public static boolean didIntegrity(String did){ - if(did.length() != 46) { + public static boolean didIntegrity(String did) { + if (did.length() != 46) { message = "Wrong DID Format (DID length: 46)"; return false; - } - else if(!did.subSequence(0, 2).equals("Qm")) { + } else if (!did.subSequence(0, 2).equals("Qm")) { message = "Wrong DID Format (DID begins with Qm)"; return false; - } - else + } else return true; } @@ -32,7 +30,7 @@ public static boolean dateIntegrity(String begin, String end) { return false; } - if(d1.compareTo(d2) > 0) { + if (d1.compareTo(d2) > 0) { message = "Begin date occurs after End date"; return false; } @@ -40,20 +38,20 @@ public static boolean dateIntegrity(String begin, String end) { } - public static boolean txnIdIntegrity(String ID){ - if(ID.length() != 64) { + public static boolean txnIdIntegrity(String ID) { + if (ID.length() != 64) { message = "Wrong Transaction ID format (Length: 64)"; return false; } return true; } - public static boolean rangeIntegrity(int a, int b){ - if(a < 0 || b < 0) { + public static boolean rangeIntegrity(int a, int b) { + if (a < 0 || b < 0) { message = "Range below bounds"; return false; } - if(a > b){ + if (a > b) { message = "Start bound larger than End bound"; return false; } diff --git a/src/com/rubix/SplitandStore/Recombine.java b/src/com/rubix/SplitandStore/Recombine.java index 3c19f97d..dd6048b8 100644 --- a/src/com/rubix/SplitandStore/Recombine.java +++ b/src/com/rubix/SplitandStore/Recombine.java @@ -1,22 +1,21 @@ package com.rubix.SplitandStore; +import static com.rubix.Resources.Functions.LOGGER_PATH; + import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; -import static com.rubix.Resources.Functions.LOGGER_PATH; - public class Recombine { public static Logger RecombineLogger = Logger.getLogger(Recombine.class); - - public static String recombine(int[] Share1, int[] Share2, int[] Share3) - { + public static String recombine(int[] Share1, int[] Share2, int[] Share3) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); StringBuilder recStr = new StringBuilder(); int payloadlength = 205; // fix the payload size here ( 33070 ) - //reconstruction with ideal contrast secret sharing, just shown an example of combining share1(essential share), share2 and share3 + // reconstruction with ideal contrast secret sharing, just shown an example of + // combining share1(essential share), share2 and share3 int[] K = new int[8 * payloadlength]; int m = 8; @@ -24,7 +23,8 @@ public static String recombine(int[] Share1, int[] Share2, int[] Share3) int[] COMB = new int[K.length * m]; int[] REC_K = new int[K.length]; // Reconstructed K - // if you need to combine share1(essential share), share3 and share4, replace the value of s0=0, s1=2 and s2=3; + // if you need to combine share1(essential share), share3 and share4, replace + // the value of s0=0, s1=2 and s2=3; for (j = 0; j < K.length * m; j++) { if (Share1[j] == 1 | Share2[j] == 1 | Share3[j] == 1) @@ -33,14 +33,14 @@ public static String recombine(int[] Share1, int[] Share2, int[] Share3) COMB[j] = 0; } -/* -System.out.println("The secret COMB"); - for(j=0;j numbers = new ArrayList<>(); @@ -88,7 +95,6 @@ public static void split(String str) { } } - x = 0; if (K[j] == 0) { do { @@ -110,87 +116,94 @@ public static void split(String str) { } SplitLogger.debug("(1,3,5) Share Generation Successful"); -//Prints the shares in console - -// for(u1=0;u1= creditsRequired) { - //String GET_URL = SYNC_IP+"/getInfo?count="+availableCredits; - + // String GET_URL = SYNC_IP+"/getInfo?count="+availableCredits; String GET_URL = SYNC_IP + "/minetoken"; URL URLobj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) URLobj.openConnection(); @@ -119,25 +154,25 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON in.close(); ProofCreditsLogger.debug("response from service " + response.toString()); - //JSONObject responseJSON=new JSONObject(response.toString()); - //resJsonData= responseJSON.getJSONArray("data"); - //creditUsed = responseJSON.getInt("credits"); + // JSONObject responseJSON=new JSONObject(response.toString()); + // resJsonData= responseJSON.getJSONArray("data"); + // creditUsed = responseJSON.getInt("credits"); resJsonData = new JSONArray(response.toString()); } else ProofCreditsLogger.debug("GET request not worked"); - - //Check if node can mine token + // Check if node can mine token if (resJsonData.length() > 0) { - //Calling Mine token function + // Calling Mine token function JSONArray token = new JSONArray(); level = resJsonData.getJSONObject(0).getInt("level"); for (int i = 0; i < resJsonData.length(); i++) { - token.put(Functions.mineToken(resJsonData.getJSONObject(i).getInt("level"), resJsonData.getJSONObject(i).getInt("token"))); + token.put(Functions.mineToken(resJsonData.getJSONObject(i).getInt("level"), + resJsonData.getJSONObject(i).getInt("token"))); creditUsed += (int) Math.pow(2, (2 + resJsonData.getJSONObject(i).getInt("level"))); @@ -146,6 +181,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON if (resJsonData.getJSONObject(0).getInt("level") == 1) creditUsed = 10; + JSONArray prooftid = new JSONArray(); String comments = resJsonData.toString() + prooftid; String authSenderByRecHash = calculateHash(token + receiverDidIpfsHash + comments, "SHA3-256"); @@ -160,8 +196,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON deleteFile(LOGGER_PATH + "tempgamma"); JSONArray quorumArray; - // JSONArray quorumArray= getQuorum(betaHash,gammaHash,receiverDidIpfsHash,receiverDidIpfsHash,token.length()); - // JSONArray quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + // JSONArray quorumArray= + // getQuorum(betaHash,gammaHash,receiverDidIpfsHash,receiverDidIpfsHash,token.length()); + // JSONArray quorumArray = new JSONArray(readFile(DATA_PATH + + // "quorumlist.json")); switch (type) { case 2: { @@ -169,7 +207,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON break; } default: { - quorumArray = getQuorum(betaHash, gammaHash, receiverDidIpfsHash, receiverDidIpfsHash, token.length()); + quorumArray = getQuorum(betaHash, gammaHash, receiverDidIpfsHash, receiverDidIpfsHash, + token.length()); } } @@ -189,14 +228,14 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.debug("betaquorum " + betaQuorum + " size " + betaQuorum.length()); ProofCreditsLogger.debug("gammaquorum " + gammaQuorum + " size " + gammaQuorum.length()); - alphaPeersList = QuorumCheck(alphaQuorum, alphaSize); betaPeersList = QuorumCheck(betaQuorum, 7); gammaPeersList = QuorumCheck(gammaQuorum, 7); // quorumPeersList = QuorumCheck(quorumArray, ipfs); - if (alphaPeersList.size() < minQuorum(alphaSize) || betaPeersList.size() < 5 || gammaPeersList.size() < 5) { + if (alphaPeersList.size() < minQuorum(alphaSize) || betaPeersList.size() < 5 + || gammaPeersList.size() < 5) { updateQuorum(quorumArray, null, false, type); APIResponse.put("did", receiverDidIpfsHash); APIResponse.put("tid", "null"); @@ -229,15 +268,15 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.debug("token mined " + token); int counter = 0; - for (int i = 0; i < balance; i++) { - JSONObject temp = records.getJSONObject(i); + + for (int i = 0; i < availableCredits; i++) { + JSONObject temp = newQstArray.getJSONObject(i); if (counter < creditUsed) { prooftid.put(temp.getString("tid")); counter++; } } - for (int i = 0; i < token.length(); i++) { writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); @@ -251,13 +290,17 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON updateJSON("add", PAYMENTS_PATH + "BNK00.json", tempArray.toString()); } - File usedCreditsFile = new File(WALLET_DATA_PATH + "MinedCreditsHistory.json"); - if(!usedCreditsFile.exists()){ - writeToFile(String.valueOf(usedCreditsFile), "[]", false); - } - writeToFile(String.valueOf(usedCreditsFile), records.toString(), false); + String creditsHistory = readFile(WALLET_DATA_PATH + "MinedCreditsHistory.json"); + JSONArray creditsHistoryArray = new JSONArray(creditsHistory); + for (int i = 0; i < creditUsed; i++) + creditsHistoryArray.put(newQstArray.getJSONObject(i)); + writeToFile(String.valueOf(usedCreditsFile), creditsHistoryArray.toString(), false); + + for (int i = 0; i < creditUsed; i++) + newQstArray.remove(i); + writeToFile(WALLET_DATA_PATH + "QuorumSignedTransactions.json", newQstArray.toString(), false); - ProofCreditsLogger.debug("Updated balance of node : " + (balance - creditUsed)); + ProofCreditsLogger.debug("Updated balance of node : " + (availableCredits - creditUsed)); long endtime = System.currentTimeMillis(); totalTime = endtime - starttime; Iterator keys = InitiatorConsensus.quorumSignature.keys(); @@ -291,17 +334,14 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON transactionRecord.put("comment", "minedtxn"); transactionRecord.put("essentialShare", InitiatorProcedure.essential); - JSONArray transactionHistoryEntry = new JSONArray(); transactionHistoryEntry.put(transactionRecord); updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); repo(ipfs); - if (!EXPLORER_IP.contains("127.0.0.1")) { - String url = EXPLORER_IP.concat("/CreateOrUpdateRubixToken"); URL obj = new URL(url); HttpsURLConnection connection_Explorer = (HttpsURLConnection) obj.openConnection(); @@ -325,7 +365,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONObject jsonObject = new JSONObject(); jsonObject.put("inputString", populate); String postJsonData = jsonObject.toString(); - // Send post request connection_Explorer.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection_Explorer.getOutputStream()); @@ -418,12 +457,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON APIResponse.put("did", receiverDidIpfsHash); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); - APIResponse.put("message", "Insufficent proofs"); + APIResponse.put("message", "Insufficient proofs"); ProofCreditsLogger.warn("Insufficient proof credits to mine"); return APIResponse; } return APIResponse; } } - - diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 05546232..58aa0b5d 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -1,32 +1,54 @@ package com.rubix.TokenTransfer; +import static com.rubix.Resources.Functions.DATA_PATH; +import static com.rubix.Resources.Functions.IPFS_PORT; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.RECEIVER_PORT; +import static com.rubix.Resources.Functions.TOKENCHAIN_PATH; +import static com.rubix.Resources.Functions.TOKENS_PATH; +import static com.rubix.Resources.Functions.WALLET_DATA_PATH; +import static com.rubix.Resources.Functions.calculateHash; +import static com.rubix.Resources.Functions.deleteFile; +import static com.rubix.Resources.Functions.getCurrentUtcTime; +import static com.rubix.Resources.Functions.getPeerID; +import static com.rubix.Resources.Functions.getValues; +import static com.rubix.Resources.Functions.nodeData; +import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.Functions.syncDataTable; +import static com.rubix.Resources.Functions.updateJSON; +import static com.rubix.Resources.Functions.writeToFile; +import static com.rubix.Resources.IPFSNetwork.add; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.get; +import static com.rubix.Resources.IPFSNetwork.listen; +import static com.rubix.Resources.IPFSNetwork.pin; +import static com.rubix.Resources.IPFSNetwork.repo; + +import java.awt.image.BufferedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.ArrayList; +import java.util.Iterator; + +import javax.imageio.ImageIO; + import com.rubix.AuthenticateNode.Authenticate; import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; -import io.ipfs.api.IPFS; + import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; - -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.*; - +import io.ipfs.api.IPFS; public class TokenReceiver { public static Logger TokenReceiverLogger = Logger.getLogger(TokenReceiver.class); @@ -37,8 +59,9 @@ public class TokenReceiver { /** * Receiver Node: To receive a valid token from an authentic sender + * * @return Transaction Details (JSONObject) - * @throws IOException handles IO Exceptions + * @throws IOException handles IO Exceptions * @throws JSONException handles JSON Exceptions */ public static String receive() { @@ -69,6 +92,7 @@ public static String receive() { long startTime = System.currentTimeMillis(); senderPeerID = input.readLine(); + syncDataTable(null, senderPeerID); String senderDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", senderPeerID); String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "peerid", senderPeerID); @@ -79,7 +103,7 @@ public static String receive() { APIResponse.put("status", "Failed"); APIResponse.put("message", "Sender details not available in network , please sync"); TokenReceiverLogger.info("Sender details not available in datatable"); - /* executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID);*/ + /* executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); */ output.close(); input.close(); @@ -88,7 +112,6 @@ public static String receive() { return APIResponse.toString(); } - nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); File senderDIDFile = new File(DATA_PATH + senderDidIpfsHash + "/DID.png"); if (!senderDIDFile.exists()) { @@ -98,7 +121,7 @@ public static String receive() { APIResponse.put("status", "Failed"); APIResponse.put("message", "Sender details not available"); TokenReceiverLogger.info("Sender details not available"); - /* executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID);*/ + /* executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); */ output.close(); input.close(); @@ -106,34 +129,25 @@ public static String receive() { ss.close(); return APIResponse.toString(); } - TokenReceiverLogger.debug("Sender details authenticated"); + // TokenReceiverLogger.debug("Sender details authenticated"); output.println("200"); String data = input.readLine(); - TokenReceiverLogger.debug("Token details received: " + data); - JSONArray TokenDetailsArray = new JSONArray(data); - JSONArray tokens = TokenDetailsArray.getJSONObject(0).getJSONArray("token"); - JSONArray tokenChains = TokenDetailsArray.getJSONObject(0).getJSONArray("tokenChain"); - String getCIDipfsHash = TokenDetailsArray.getJSONObject(1).getString("ipfsHash"); - TokenReceiverLogger.debug("Checking providers for: " + getCIDipfsHash); - ArrayList dhtOwnersList = dhtOwnerCheck(getCIDipfsHash); - TokenReceiverLogger.debug("Providers: " + dhtOwnersList); - TokenReceiverLogger.debug("IPFS get of consensusFile: " + getCIDipfsHash); - String consensusID = get(getCIDipfsHash, ipfs); - - + // TokenReceiverLogger.debug("Token details received: "); + JSONObject TokenDetails = new JSONObject(data); + JSONArray tokens = TokenDetails.getJSONArray("token"); + JSONArray tokenChains = TokenDetails.getJSONArray("tokenChain"); + JSONArray tokenHeader = TokenDetails.getJSONArray("tokenHeader"); int tokenCount = tokens.length(); - String senderToken = TokenDetailsArray.getJSONObject(0).toString(); + String senderToken = TokenDetails.toString(); - String consensusIdCompare = calculateHash(senderToken, "SHA3-256"); -// writeToFile(LOGGER_PATH + "consensusID", consensusID, false); -// String consensusIDIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "consensusID", ipfs); -// deleteFile(LOGGER_PATH + "consensusID"); + String consensusID = calculateHash(senderToken, "SHA3-256"); + writeToFile(LOGGER_PATH + "consensusID", consensusID, false); + String consensusIDIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "consensusID", ipfs); + deleteFile(LOGGER_PATH + "consensusID"); - - - //Check IPFS get for all Tokens + // Check IPFS get for all Tokens int ipfsGetFlag = 0; ArrayList allTokenContent = new ArrayList<>(); ArrayList allTokenChainContent = new ArrayList<>(); @@ -144,45 +158,31 @@ public static String receive() { allTokenContent.add(TokenContent); ipfsGetFlag++; } - if(!consensusID.equals(consensusIdCompare)){ - String errorMessage = "Consensus ID not unique: Hashes do not match - " + "Sent " + consensusID + " Recalculated " + consensusIdCompare; + repo(ipfs); + + if (!IPFSNetwork.dhtEmpty(consensusIDIPFSHash, ipfs)) { + TokenReceiverLogger.debug("consensus ID not unique" + consensusIDIPFSHash); output.println("420"); APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); - APIResponse.put("message", errorMessage); - TokenReceiverLogger.debug(errorMessage); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + APIResponse.put("message", "Consensus ID not unique"); + TokenReceiverLogger.info("Consensus ID not unique"); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); output.close(); input.close(); sk.close(); ss.close(); return APIResponse.toString(); } - else if(!(dhtOwnersList.size() == 1 && dhtOwnersList.contains(senderPeerID))){ - String errorMessage = "Consensus ID not unique: " + dhtOwnersList.size() + " owns the hash " + dhtOwnersList; + if (!(ipfsGetFlag == tokenCount)) { output.println("421"); APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); - APIResponse.put("message", errorMessage); - TokenReceiverLogger.debug(errorMessage); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - else if(!(ipfsGetFlag == tokenCount)){ - String errorMessage = "Tokens not verified"; - output.println("422"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", errorMessage); - TokenReceiverLogger.debug(errorMessage); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + APIResponse.put("message", "Tokens not verified"); + TokenReceiverLogger.info("Tokens not verified"); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); output.close(); input.close(); sk.close(); @@ -190,13 +190,9 @@ else if(!(ipfsGetFlag == tokenCount)){ return APIResponse.toString(); } - repo(ipfs); output.println("200"); - String senderDetails = input.readLine(); - - JSONObject SenderDetails = new JSONObject(senderDetails); String senderSignature = SenderDetails.getString("sign"); String tid = SenderDetails.getString("tid"); @@ -211,20 +207,21 @@ else if(!(ipfsGetFlag == tokenCount)){ TokenReceiverLogger.debug("Consensus Status: " + Status); + TokenReceiverLogger.debug("Verifying Quorum ... "); + TokenReceiverLogger.debug("Please wait, this might take a few seconds"); + if (!Status.equals("Consensus Failed")) { boolean yesQuorum = false; if (Status.equals("Consensus Reached")) { -// String QuorumDetails = input.readLine(); - -// TokenReceiverLogger.debug("Quorum Signatures: " + QuorumDetails); + TokenReceiverLogger.debug("Quorum Signatures: " + QuorumDetails); quorumSignatures = new JSONObject(QuorumDetails); int alphaSize = quorumSignatures.length() - 10; - -// String selectQuorumHash = calculateHash(senderToken, "SHA3-256"); - - String verifyQuorumHash = calculateHash(getCIDipfsHash.concat(receiverDidIpfsHash), "SHA3-256"); -// TokenReceiverLogger.debug("Quorum Hash on Receiver Side " + verifyQuorumHash); -// TokenReceiverLogger.debug("Quorum Signatures length : " + quorumSignatures.length()); + String selectQuorumHash = calculateHash(senderToken, "SHA3-256"); + String verifyQuorumHash = calculateHash(selectQuorumHash.concat(receiverDidIpfsHash), "SHA3-256"); + TokenReceiverLogger.debug("1: " + selectQuorumHash); + TokenReceiverLogger.debug("2: " + receiverDidIpfsHash); + TokenReceiverLogger.debug("Quorum Hash on Receiver Side " + verifyQuorumHash); + TokenReceiverLogger.debug("Quorum Signatures length : " + quorumSignatures.length()); Iterator keys = quorumSignatures.keys(); while (keys.hasNext()) { @@ -233,15 +230,11 @@ else if(!(ipfsGetFlag == tokenCount)){ } for (String quorumDidIpfsHash : quorumDID) { - String quorumWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", quorumDidIpfsHash); - - File quorumDataFolder = new File(DATA_PATH + quorumDidIpfsHash + "/"); - if (!quorumDataFolder.exists()) { - quorumDataFolder.mkdirs(); - IPFSNetwork.getImage(quorumDidIpfsHash, ipfs, DATA_PATH + quorumDidIpfsHash + "/DID.png"); - IPFSNetwork.getImage(quorumWidIpfsHash, ipfs, DATA_PATH + quorumDidIpfsHash + "/PublicShare.png"); -// TokenReceiverLogger.debug("Quorum Data " + quorumDidIpfsHash + " Added"); - } + syncDataTable(quorumDidIpfsHash, null); + String quorumWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", + quorumDidIpfsHash); + + nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); } for (int i = 0; i < quorumSignatures.length(); i++) { @@ -261,7 +254,9 @@ else if(!(ipfsGetFlag == tokenCount)){ for (int i = 0; i < tokenCount; i++) allTokensChainsPushed.add(tokenChains.getString(i)); - String hash = calculateHash(tokens.toString() + allTokensChainsPushed.toString() + receiverDidIpfsHash + comment, "SHA3-256"); + String hash = calculateHash( + tokens.toString() + allTokensChainsPushed.toString() + receiverDidIpfsHash + comment, + "SHA3-256"); JSONObject detailsForVerify = new JSONObject(); detailsForVerify.put("did", senderDidIpfsHash); @@ -269,8 +264,7 @@ else if(!(ipfsGetFlag == tokenCount)){ detailsForVerify.put("signature", senderSignature); boolean yesSender = Authenticate.verifySignature(detailsForVerify.toString()); -// TokenReceiverLogger.debug("Sender auth hash " + hash); -// TokenReceiverLogger.debug("Quorum Auth : " + yesQuorum + "Sender Auth : " + yesSender); + TokenReceiverLogger.debug("Quorum Auth : " + yesQuorum + "Sender Auth : " + yesSender); if (!(yesSender && yesQuorum)) { output.println("420"); APIResponse.put("did", senderDidIpfsHash); @@ -278,7 +272,7 @@ else if(!(ipfsGetFlag == tokenCount)){ APIResponse.put("status", "Failed"); APIResponse.put("message", "Sender / Quorum not verified"); TokenReceiverLogger.info("Sender / Quorum not verified"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); output.close(); input.close(); sk.close(); @@ -348,7 +342,8 @@ else if(!(ipfsGetFlag == tokenCount)){ JSONArray transactionHistoryEntry = new JSONArray(); transactionHistoryEntry.put(transactionRecord); - updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); + updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", + transactionHistoryEntry.toString()); TokenReceiverLogger.info("Transaction ID: " + tid + "Transaction Successful"); output.println("Send Response"); @@ -356,9 +351,10 @@ else if(!(ipfsGetFlag == tokenCount)){ APIResponse.put("tid", tid); APIResponse.put("status", "Success"); APIResponse.put("tokens", tokens); + APIResponse.put("tokenHeader", tokenHeader); APIResponse.put("comment", comment); APIResponse.put("message", "Transaction Successful"); -// TokenReceiverLogger.info(" Transaction Successful"); + TokenReceiverLogger.info(" Transaction Successful"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); output.close(); input.close(); @@ -407,13 +403,11 @@ else if(!(ipfsGetFlag == tokenCount)){ ss.close(); return APIResponse.toString(); - } - catch (Exception e) { + } catch (Exception e) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); TokenReceiverLogger.error("Exception Occurred", e); return APIResponse.toString(); - } - finally{ + } finally { try { ss.close(); sk.close(); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index d95b8146..7ac8febe 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -1,54 +1,85 @@ package com.rubix.TokenTransfer; -import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Consensus.InitiatorConsensus; +import static com.rubix.Constants.ConsensusConstants.DATA; +import static com.rubix.Constants.ConsensusConstants.PRIMARY; +import static com.rubix.Constants.ConsensusConstants.TRANS_TYPE; +import static com.rubix.Resources.Functions.DATA_PATH; +import static com.rubix.Resources.Functions.EXPLORER_IP; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.QuorumCheck; +import static com.rubix.Resources.Functions.QuorumSwarmConnect; +import static com.rubix.Resources.Functions.SEND_PORT; +import static com.rubix.Resources.Functions.TOKENCHAIN_PATH; +import static com.rubix.Resources.Functions.TOKENS_PATH; +import static com.rubix.Resources.Functions.WALLET_DATA_PATH; +import static com.rubix.Resources.Functions.calculateHash; +import static com.rubix.Resources.Functions.deleteFile; +import static com.rubix.Resources.Functions.getCurrentUtcTime; +import static com.rubix.Resources.Functions.getPeerID; +import static com.rubix.Resources.Functions.getQuorum; +import static com.rubix.Resources.Functions.getSignFromShares; +import static com.rubix.Resources.Functions.getValues; +import static com.rubix.Resources.Functions.minQuorum; +import static com.rubix.Resources.Functions.nodeData; +import static com.rubix.Resources.Functions.readFile; +import static com.rubix.Resources.Functions.syncDataTable; +import static com.rubix.Resources.Functions.updateJSON; +import static com.rubix.Resources.Functions.updateQuorum; +import static com.rubix.Resources.Functions.writeToFile; +import static com.rubix.Resources.IPFSNetwork.add; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.forward; +import static com.rubix.Resources.IPFSNetwork.repo; +import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; +import static com.rubix.Resources.IPFSNetwork.unpin; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.Socket; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import javax.net.ssl.HttpsURLConnection; + +import com.rubix.Consensus.InitiatorConsensus; import com.rubix.Consensus.InitiatorProcedure; -import com.rubix.Consensus.QuorumConsensus; -import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; -import io.ipfs.api.IPFS; + import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import javax.imageio.ImageIO; -import javax.net.ssl.HttpsURLConnection; -import java.awt.image.BufferedImage; -import java.io.*; -import java.net.HttpURLConnection; -import java.net.Socket; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.NoSuchAlgorithmException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.util.*; - -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.*; - +import io.ipfs.api.IPFS; public class TokenSender { private static final Logger TokenSenderLogger = Logger.getLogger(TokenSender.class); + private static final Logger eventLogger = Logger.getLogger("eventLogger"); + private static final String USER_AGENT = "Mozilla/5.0"; public static BufferedReader serverInput; private static PrintStream output; private static BufferedReader input; private static Socket senderSocket; private static boolean senderMutex = false; -// private static int heartBeatAlpha=0; -// private static int heartBeatBeta=0; -// private static int heartBeatGamma=0; -// private static int alphaSize=0; -// -// private static ArrayList alphaPeersList; -// private static ArrayList betaPeersList; -// private static ArrayList gammaPeersList; + // private static int heartBeatAlpha=0; + // private static int heartBeatBeta=0; + // private static int heartBeatGamma=0; + // private static int alphaSize=0; + // + // private static ArrayList alphaPeersList; + // private static ArrayList betaPeersList; + // private static ArrayList gammaPeersList; /** * A sender node to transfer tokens @@ -63,18 +94,10 @@ public class TokenSender { */ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception { - JSONObject APIResponse = new JSONObject(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String receiverPeerId; - JSONObject detailsObject = new JSONObject(data); - String receiverDidIpfsHash = detailsObject.getString("receiverDidIpfsHash"); - String pvt = detailsObject.getString("pvt"); - int amount = detailsObject.getInt("amount"); - int type = detailsObject.getInt("type"); - String comment = detailsObject.getString("comment"); - JSONArray tokens = detailsObject.getJSONArray("tokens"); - JSONArray tokenHeader = detailsObject.getJSONArray("tokenHeader"); + JSONArray quorumArray; JSONArray alphaQuorum = new JSONArray(); JSONArray betaQuorum = new JSONArray(); @@ -93,19 +116,10 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String senderDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", senderPeerID); TokenSenderLogger.debug("sender did ipfs hash" + senderDidIpfsHash); TokenSenderLogger.debug("path is" + DATA_PATH + senderDidIpfsHash); - File folder = new File(DATA_PATH + senderDidIpfsHash); - File[] listOfFiles = folder.listFiles(); - for (int i = 0; i < listOfFiles.length; i++) { - if (listOfFiles[i].isFile()) { - System.out.println("File " + listOfFiles[i].getName()); - } else if (listOfFiles[i].isDirectory()) { - System.out.println("Directory " + listOfFiles[i].getName()); - } - } - - BufferedImage senderWidImage = ImageIO.read(new File(DATA_PATH + senderDidIpfsHash + "/PublicShare.png")); - String senderWidBin = PropImage.img2bin(senderWidImage); + // BufferedImage senderWidImage = ImageIO.read(new File(DATA_PATH + + // senderDidIpfsHash + "/PublicShare.png")); + // String senderWidBin = PropImage.img2bin(senderWidImage); if (senderMutex) { APIResponse.put("did", senderDidIpfsHash); @@ -118,6 +132,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception senderMutex = true; + JSONObject detailsObject = new JSONObject(data); + int type = detailsObject.getInt("type"); + String comment = detailsObject.getString("comment"); + String pvt = detailsObject.getString("pvt"); + JSONArray tokens = detailsObject.getJSONArray("tokens"); + String peerAuth; ArrayList allTokensChainsPushed = new ArrayList(); APIResponse = new JSONObject(); @@ -134,7 +154,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception for (int i = 0; i < tokens.length(); i++) { File token = new File(TOKENS_PATH + tokens.get(i)); File tokenchain = new File(TOKENCHAIN_PATH + tokens.get(i) + ".json"); - TokenSenderLogger.debug(token + "and " + tokenchain); + TokenSenderLogger.debug(token + " and " + tokenchain); if (!(token.exists() && tokenchain.exists())) { TokenSenderLogger.info("Tokens Not Verified"); senderMutex = false; @@ -145,469 +165,1026 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } + // String hash = add(TOKENS_PATH + tokens.get(i), ipfs); + // pin(hash, ipfs); add(TOKENS_PATH + tokens.get(i), ipfs); String tokenChainHash = add(TOKENCHAIN_PATH + tokens.get(i) + ".json", ipfs); allTokensChainsPushed.add(tokenChainHash); } - String authSenderByRecHash = calculateHash(tokens.toString() + allTokensChainsPushed.toString() + receiverDidIpfsHash + comment, "SHA3-256"); - String tid = calculateHash(authSenderByRecHash, "SHA3-256"); - TokenSenderLogger.debug("Sender by Receiver Hash " + authSenderByRecHash); - TokenSenderLogger.debug("TID on sender " + tid); + TokenSenderLogger.debug("All tokens added"); - writeToFile(LOGGER_PATH + "tempbeta", tid.concat(senderDidIpfsHash), false); - String betaHash = IPFSNetwork.add(LOGGER_PATH + "tempbeta", ipfs); - deleteFile(LOGGER_PATH + "tempbeta"); - - writeToFile(LOGGER_PATH + "tempgamma", tid.concat(receiverDidIpfsHash), false); - String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); - deleteFile(LOGGER_PATH + "tempgamma"); - - - switch (type) { - case 1: { - quorumArray = getQuorum(betaHash, gammaHash, senderDidIpfsHash, receiverDidIpfsHash, tokens.length()); - break; - } - - case 2: { - quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); - break; - } - case 3: { - quorumArray = detailsObject.getJSONArray("quorum"); - break; - } - default: { - TokenSenderLogger.error("Unknown quorum type input, cancelling transaction"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Unknown quorum type input, cancelling transaction"); - return APIResponse; - - } + // check if detailsObject contains TRANC_TYPE + if (!detailsObject.has(TRANS_TYPE)) { + APIResponse.put("ERROR", "TRANS_TYPE not found"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "TRANS_TYPE not found"); + return APIResponse; } - QuorumSwarmConnect(quorumArray, ipfs); + TokenSenderLogger.debug("Initiating transaction type:" + detailsObject.has(TRANS_TYPE)); - alphaSize = quorumArray.length() - 14; - - for (int i = 0; i < alphaSize; i++) - alphaQuorum.put(quorumArray.getString(i)); - - for (int i = 0; i < 7; i++) { - betaQuorum.put(quorumArray.getString(alphaSize + i)); - gammaQuorum.put(quorumArray.getString(alphaSize + 7 + i)); - } + if (detailsObject.getString(TRANS_TYPE) == PRIMARY) { - TokenSenderLogger.debug("alphaquorum " + alphaQuorum + " size " + alphaQuorum.length()); - TokenSenderLogger.debug("betaquorum " + betaQuorum + " size " + betaQuorum.length()); - TokenSenderLogger.debug("gammaquorum " + gammaQuorum + " size " + gammaQuorum.length()); + String receiverDidIpfsHash = detailsObject.getString("receiverDidIpfsHash"); + int amount = detailsObject.getInt("amount"); + JSONArray tokenHeader = detailsObject.getJSONArray("tokenHeader"); + String authSenderByRecHash = calculateHash( + tokens.toString() + allTokensChainsPushed.toString() + receiverDidIpfsHash + comment, "SHA3-256"); + String tid = calculateHash(authSenderByRecHash, "SHA3-256"); + TokenSenderLogger.debug("Sender by Receiver Hash " + authSenderByRecHash); + TokenSenderLogger.debug("TID on sender " + tid); - alphaPeersList = QuorumCheck(alphaQuorum, alphaSize); - betaPeersList = QuorumCheck(betaQuorum, 7); - gammaPeersList = QuorumCheck(gammaQuorum, 7); + writeToFile(LOGGER_PATH + "tempbeta", tid.concat(senderDidIpfsHash), false); + String betaHash = IPFSNetwork.add(LOGGER_PATH + "tempbeta", ipfs); + deleteFile(LOGGER_PATH + "tempbeta"); -// for(int i=0;i= minQuorum(7))) { + TokenSenderLogger.debug("Consensus Failed"); + senderDetails2Receiver.put("status", "Consensus Failed"); + senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); + output.println(senderDetails2Receiver); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; + updateQuorum(quorumArray, null, false, type); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", tid); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Transaction declined by Quorum"); + return APIResponse; + } -// DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); -// Date date = new Date(); -// -// LocalDate currentTime = LocalDate.parse(formatter.format(date).replace("/", "-")); - receiverPeerId = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", receiverDidIpfsHash); + TokenSenderLogger.debug("Consensus Reached"); + senderDetails2Receiver.put("status", "Consensus Reached"); + senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); - TokenSenderLogger.debug("Swarm connecting to " + receiverPeerId); - swarmConnectP2P(receiverPeerId, ipfs); - TokenSenderLogger.debug("Swarm connected"); + output.println(senderDetails2Receiver); + // output.println("Consensus Reached"); + TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); + // output.println(InitiatorConsensus.quorumSignature); + + String signatureAuth = input.readLine(); + TokenSenderLogger.info("signatureAuth : " + signatureAuth); + endTime = System.currentTimeMillis(); + totalTime = endTime - startTime; + if (!signatureAuth.equals("200")) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + TokenSenderLogger.info("Authentication Failed"); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; + updateQuorum(quorumArray, null, false, type); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", tid); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender not authenticated"); + return APIResponse; - String receiverWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", receiverDidIpfsHash); - nodeData(receiverDidIpfsHash, receiverWidIpfsHash, ipfs); + } - forward(receiverPeerId, port, receiverPeerId); + for (int i = 0; i < tokens.length(); i++) + unpin(String.valueOf(tokens.get(i)), ipfs); + + // unpin(consensusIDIPFSHash, ipfs); + repo(ipfs); + + TokenSenderLogger.debug("Unpinned Tokens"); + output.println("Unpinned"); + String confirmation = input.readLine(); + + if (!confirmation.equals("Successfully Pinned")) { + TokenSenderLogger.warn("Multiple Owners for the token"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + TokenSenderLogger.info("Tokens with multiple pins"); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; + updateQuorum(quorumArray, null, false, type); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", tid); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Tokens with multiple pins"); + return APIResponse; - TokenSenderLogger.debug("Forwarded to " + receiverPeerId + " on " + port); - senderSocket = new Socket("127.0.0.1", port); + } + output.println(InitiatorProcedure.essential); + String respAuth = input.readLine(); - input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); - output = new PrintStream(senderSocket.getOutputStream()); + if (!respAuth.equals("Send Response")) { - long startTime = System.currentTimeMillis(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; + updateQuorum(quorumArray, null, false, type); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", tid); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Receiver process not over"); + TokenSenderLogger.info("Incomplete Transaction"); + return APIResponse; - output.println(senderPeerID); - TokenSenderLogger.debug("Sent PeerID"); + } - peerAuth = input.readLine(); + Iterator keys = InitiatorConsensus.quorumSignature.keys(); + JSONArray signedQuorumList = new JSONArray(); + while (keys.hasNext()) + signedQuorumList.put(keys.next()); + APIResponse.put("tid", tid); + APIResponse.put("status", "Success"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("message", "Tokens transferred successfully!"); + APIResponse.put("quorumlist", signedQuorumList); + APIResponse.put("receiver", receiverDidIpfsHash); + APIResponse.put("totaltime", totalTime); + + updateQuorum(quorumArray, signedQuorumList, true, type); + + JSONObject transactionRecord = new JSONObject(); + transactionRecord.put("role", "Sender"); + transactionRecord.put("tokens", tokens); + transactionRecord.put("txn", tid); + transactionRecord.put("quorumList", signedQuorumList); + transactionRecord.put("senderDID", senderDidIpfsHash); + transactionRecord.put("receiverDID", receiverDidIpfsHash); + transactionRecord.put("Date", getCurrentUtcTime()); + transactionRecord.put("totalTime", totalTime); + transactionRecord.put("comment", comment); + transactionRecord.put("essentialShare", InitiatorProcedure.essential); + + JSONArray transactionHistoryEntry = new JSONArray(); + transactionHistoryEntry.put(transactionRecord); + + updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); + for (int i = 0; i < tokens.length(); i++) + Files.deleteIfExists(Paths.get(TOKENS_PATH + tokens.get(i))); + + // Populating data to explorer + if (!EXPLORER_IP.contains("127.0.0.1")) { + startTime = System.currentTimeMillis(); + List tokenList = new ArrayList<>(); + for (int i = 0; i < tokens.length(); i++) + tokenList.add(tokens.getString(i)); + String url = EXPLORER_IP + "/CreateOrUpdateRubixTransaction"; + URL obj = new URL(url); + HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); + + // Setting basic post request + con.setRequestMethod("POST"); + con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("Content-Type", "application/json"); + con.setRequestProperty("Authorization", "null"); + + // Serialization + JSONObject dataToSend = new JSONObject(); + dataToSend.put("transaction_id", tid); + dataToSend.put("sender_did", senderDidIpfsHash); + dataToSend.put("receiver_did", receiverDidIpfsHash); + dataToSend.put("token_id", tokenList); + dataToSend.put("token_time", (int) totalTime); + dataToSend.put("amount", amount); + String populate = dataToSend.toString(); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("inputString", populate); + String postJsonData = jsonObject.toString(); + + // Send post request + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(postJsonData); + wr.flush(); + wr.close(); + + int responseCode = con.getResponseCode(); + TokenSenderLogger.debug("Sending 'POST' request to URL : " + url); + TokenSenderLogger.debug("Post Data : " + postJsonData); + TokenSenderLogger.debug("Response Code : " + responseCode); + + BufferedReader in = new BufferedReader( + new InputStreamReader(con.getInputStream())); + String output; + StringBuffer response = new StringBuffer(); + + while ((output = in.readLine()) != null) { + response.append(output); + } + in.close(); + + endTime = System.currentTimeMillis(); + TokenSenderLogger.debug(response.toString()); + } -// while ((peerAuth = input.readLine()) == null) { -//// forward(receiverPeerId, port, receiverPeerId); -//// senderSocket = new Socket("127.0.0.1", port); -//// input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); -//// output = new PrintStream(senderSocket.getOutputStream()); -//// output.println(senderPeerID); -// } - if (!peerAuth.equals("200")) { + // + // if (type==1) { + // String urlQuorumUpdate = SYNC_IP+"/updateQuorum"; + // URL objQuorumUpdate = new URL(urlQuorumUpdate); + // HttpURLConnection conQuorumUpdate = (HttpURLConnection) + // objQuorumUpdate.openConnection(); + // + // conQuorumUpdate.setRequestMethod("POST"); + // conQuorumUpdate.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); + // conQuorumUpdate.setRequestProperty("Accept", "application/json"); + // conQuorumUpdate.setRequestProperty("Content-Type", "application/json"); + // conQuorumUpdate.setRequestProperty("Authorization", "null"); + // + // JSONObject dataToSendQuorumUpdate = new JSONObject(); + // dataToSendQuorumUpdate.put("completequorum", quorumArray); + // dataToSendQuorumUpdate.put("signedquorum",signedQuorumList); + // String populateQuorumUpdate = dataToSendQuorumUpdate.toString(); + // + // conQuorumUpdate.setDoOutput(true); + // DataOutputStream wrQuorumUpdate = new + // DataOutputStream(conQuorumUpdate.getOutputStream()); + // wrQuorumUpdate.writeBytes(populateQuorumUpdate); + // wrQuorumUpdate.flush(); + // wrQuorumUpdate.close(); + // + // int responseCodeQuorumUpdate = conQuorumUpdate.getResponseCode(); + // TokenSenderLogger.debug("Sending 'POST' request to URL : " + + // urlQuorumUpdate); + // TokenSenderLogger.debug("Post Data : " + populateQuorumUpdate); + // TokenSenderLogger.debug("Response Code : " + responseCodeQuorumUpdate); + // + // BufferedReader inQuorumUpdate = new BufferedReader( + // new InputStreamReader(conQuorumUpdate.getInputStream())); + // String outputQuorumUpdate; + // StringBuffer responseQuorumUpdate = new StringBuffer(); + // while ((outputQuorumUpdate = inQuorumUpdate.readLine()) != null) { + // responseQuorumUpdate.append(outputQuorumUpdate); + // } + // inQuorumUpdate.close(); + // + // } + + TokenSenderLogger.info("Transaction Successful"); + // System.out.println("Verify Count: " + Authenticate.verifyCount); + // Authenticate.verifyCount = 0; executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - TokenSenderLogger.info("Sender Data Not Available"); output.close(); input.close(); senderSocket.close(); - senderMutex = false; - updateQuorum(quorumArray, null, false, type); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", tid); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Data Not Available"); - return APIResponse; } - output.println(tokenBindDetailsArray); + if (detailsObject.getString(TRANS_TYPE) == DATA) { - String tokenAuth = input.readLine(); + String blockHash = detailsObject.getString("blockHash"); + int amount = detailsObject.getInt("amount"); + JSONArray tokenHeader = detailsObject.getJSONArray("tokenHeader"); - if (!tokenAuth.equals("200")) { - String errorMessage = null; - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + String authSenderByRecHash = calculateHash( + tokens.toString() + allTokensChainsPushed.toString() + blockHash + comment, "SHA3-256"); + String tid = calculateHash(authSenderByRecHash, "SHA3-256"); + TokenSenderLogger.debug("Sender by Receiver Hash " + authSenderByRecHash); + TokenSenderLogger.debug("TID on sender " + tid); - output.close(); - input.close(); - senderSocket.close(); - senderMutex = false; - switch (tokenAuth) { - case "420": - errorMessage = "Consensus ID not unique: Hashes do not match"; + writeToFile(LOGGER_PATH + "tempbeta", tid.concat(senderDidIpfsHash), false); + String betaHash = IPFSNetwork.add(LOGGER_PATH + "tempbeta", ipfs); + deleteFile(LOGGER_PATH + "tempbeta"); + + writeToFile(LOGGER_PATH + "tempgamma", tid.concat(blockHash), false); + String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); + deleteFile(LOGGER_PATH + "tempgamma"); + + long startTime = System.currentTimeMillis(); + switch (type) { + case 1: { + quorumArray = getQuorum(betaHash, gammaHash, senderDidIpfsHash, + blockHash, + tokens.length()); break; - case "421": - errorMessage = "Consensus ID not unique: More than one provider for consensus ID hash"; + } + + case 2: { + quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); break; - case "422": - errorMessage = "Tokens not verified"; + } + case 3: { + quorumArray = detailsObject.getJSONArray("quorum"); break; + } + default: { + TokenSenderLogger.error("Unknown quorum type input, cancelling transaction"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Unknown quorum type input, cancelling transaction"); + return APIResponse; + + } } + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + eventLogger.debug("Get Quorum List " + totalTime); - TokenSenderLogger.info(errorMessage); - updateQuorum(quorumArray, null, false, type); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", tid); - APIResponse.put("status", "Failed"); - APIResponse.put("message", errorMessage); - - return APIResponse; - - } - - // output.println(senderDetails2Receiver); - + startTime = System.currentTimeMillis(); + QuorumSwarmConnect(quorumArray, ipfs); + endTime = System.currentTimeMillis(); + totalTime = endTime - startTime; + eventLogger.debug("Swarm Connect " + totalTime); - JSONObject dataObject = new JSONObject(); - dataObject.put("tid", tid); - dataObject.put("message", consensusIDIPFSHash); - dataObject.put("receiverDidIpfs", receiverDidIpfsHash); - dataObject.put("pvt", pvt); - dataObject.put("senderDidIpfs", senderDidIpfsHash); - dataObject.put("token", tokens.toString()); - dataObject.put("alphaList", alphaPeersList); - dataObject.put("betaList", betaPeersList); - dataObject.put("gammaList", gammaPeersList); + alphaSize = quorumArray.length() - 14; - TokenSenderLogger.debug("dataobject " + dataObject.toString()); - - InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 100, alphaSize); - TokenSenderLogger.debug("length on sender " + InitiatorConsensus.quorumSignature.length() + "response count " + InitiatorConsensus.quorumResponse); - if (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { - // if (!(InitiatorProcedure.alphaReply.length() >= minQuorum(7))) { - TokenSenderLogger.debug("Consensus Failed"); - senderDetails2Receiver.put("status", "Consensus Failed"); - senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); - output.println(senderDetails2Receiver); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - output.close(); - input.close(); - senderSocket.close(); - senderMutex = false; - updateQuorum(quorumArray, null, false, type); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", tid); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Transaction declined by Quorum"); - return APIResponse; + for (int i = 0; i < alphaSize; i++) + alphaQuorum.put(quorumArray.getString(i)); - } + for (int i = 0; i < 7; i++) { + betaQuorum.put(quorumArray.getString(alphaSize + i)); + gammaQuorum.put(quorumArray.getString(alphaSize + 7 + i)); + } - TokenSenderLogger.debug("Consensus Reached"); - senderDetails2Receiver.put("status", "Consensus Reached"); - senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); + TokenSenderLogger.debug("alphaquorum " + alphaQuorum + " size " + alphaQuorum.length()); + TokenSenderLogger.debug("betaquorum " + betaQuorum + " size " + betaQuorum.length()); + TokenSenderLogger.debug("gammaquorum " + gammaQuorum + " size " + gammaQuorum.length()); + + // Commented by Anuradha K; A new method checkQuorum is implemented to check + // Quorum + /* + * alphaPeersList=QuorumCheck(alphaQuorum,ipfs,alphaSize); betaPeersList= + * QuorumCheck(betaQuorum,ipfs,7); + * gammaPeersList=QuorumCheck(gammaQuorum,ipfs,7); + */ + startTime = System.currentTimeMillis(); + + alphaPeersList = QuorumCheck(alphaQuorum, alphaSize); + betaPeersList = QuorumCheck(betaQuorum, 7); + gammaPeersList = QuorumCheck(gammaQuorum, 7); + + endTime = System.currentTimeMillis(); + totalTime = endTime - startTime; + eventLogger.debug("Quorum Check " + totalTime); + // for(int i=0;i= minQuorum(7))) { + TokenSenderLogger.debug("Consensus Failed"); + // senderDetails2Receiver.put("status", "Consensus Failed"); + // senderDetails2Receiver.put("quorumsign", + // InitiatorConsensus.quorumSignature.toString()); + // output.println(senderDetails2Receiver); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; + updateQuorum(quorumArray, null, false, type); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", tid); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Transaction declined by Quorum"); + return APIResponse; - String signatureAuth = input.readLine(); + } - long endAuth = System.currentTimeMillis(); - long totalTime = endAuth - startTime; - if (!signatureAuth.equals("200")) { - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - TokenSenderLogger.info("Authentication Failed"); - output.close(); - input.close(); - senderSocket.close(); - senderMutex = false; - updateQuorum(quorumArray, null, false, type); - APIResponse.put("did", senderDidIpfsHash); + TokenSenderLogger.debug("Consensus Reached"); + // senderDetails2Receiver.put("status", "Consensus Reached"); + // senderDetails2Receiver.put("quorumsign", + // InitiatorConsensus.quorumSignature.toString()); + + // output.println(senderDetails2Receiver); + // output.println("Consensus Reached"); + TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); + // output.println(InitiatorConsensus.quorumSignature); + + // String signatureAuth = input.readLine(); + // TokenSenderLogger.info("signatureAuth : " + signatureAuth); + // endTime = System.currentTimeMillis(); + // totalTime = endTime - startTime; + // if (!signatureAuth.equals("200")) { + // // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + // TokenSenderLogger.info("Authentication Failed"); + // output.close(); + // input.close(); + // senderSocket.close(); + // senderMutex = false; + // updateQuorum(quorumArray, null, false, type); + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", tid); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Sender not authenticated"); + // return APIResponse; + + // } + + // for (int i = 0; i < tokens.length(); i++) + // unpin(String.valueOf(tokens.get(i)), ipfs); + + // unpin(consensusIDIPFSHash, ipfs); + // repo(ipfs); + + // TokenSenderLogger.debug("Unpinned data"); + // output.println("Unpinned"); + // String confirmation = input.readLine(); + + // if (!confirmation.equals("Successfully Pinned")) { + // TokenSenderLogger.warn("Multiple Owners for the token"); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + // TokenSenderLogger.info("Tokens with multiple pins"); + // output.close(); + // input.close(); + // senderSocket.close(); + // senderMutex = false; + // updateQuorum(quorumArray, null, false, type); + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", tid); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Tokens with multiple pins"); + // return APIResponse; + + // } + // output.println(InitiatorProcedure.essential); + // String respAuth = input.readLine(); + + // if (!respAuth.equals("Send Response")) { + + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + // output.close(); + // input.close(); + // senderSocket.close(); + // senderMutex = false; + // updateQuorum(quorumArray, null, false, type); + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", tid); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Block commit process not over"); + // TokenSenderLogger.info("Incomplete Data Transaction"); + // return APIResponse; + + // } + + Iterator keys = InitiatorConsensus.quorumSignature.keys(); + JSONArray signedQuorumList = new JSONArray(); + while (keys.hasNext()) + signedQuorumList.put(keys.next()); APIResponse.put("tid", tid); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender not authenticated"); - return APIResponse; - - } - - for (int i = 0; i < tokens.length(); i++) - unpin(String.valueOf(tokens.get(i)), ipfs); - - unpin(consensusIDIPFSHash, ipfs); - - repo(ipfs); - - TokenSenderLogger.debug("Unpinned Tokens"); - output.println("Unpinned"); - - String confirmation = input.readLine(); - if (!confirmation.equals("Successfully Pinned")) { - TokenSenderLogger.warn("Multiple Owners for the token"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - TokenSenderLogger.info("Tokens with multiple pins"); - output.close(); - input.close(); - senderSocket.close(); - senderMutex = false; - updateQuorum(quorumArray, null, false, type); + APIResponse.put("status", "Success"); APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", tid); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Tokens with multiple pins"); - return APIResponse; - - } - output.println(InitiatorProcedure.essential); - String respAuth = input.readLine(); - - if (!respAuth.equals("Send Response")) { + APIResponse.put("message", "Data Block Committed successfully!"); + APIResponse.put("quorumlist", signedQuorumList); + APIResponse.put("blockHash", blockHash); + APIResponse.put("totaltime", totalTime); + + updateQuorum(quorumArray, signedQuorumList, true, type); + + JSONObject transactionRecord = new JSONObject(); + transactionRecord.put("role", "Sender"); + transactionRecord.put("tokens", tokens); + transactionRecord.put("txn", tid); + transactionRecord.put("quorumList", signedQuorumList); + transactionRecord.put("senderDID", senderDidIpfsHash); + transactionRecord.put("blockHash", blockHash); + transactionRecord.put("Date", getCurrentUtcTime()); + transactionRecord.put("totalTime", totalTime); + transactionRecord.put("comment", comment); + transactionRecord.put("essentialShare", InitiatorProcedure.essential); + + JSONArray transactionHistoryEntry = new JSONArray(); + transactionHistoryEntry.put(transactionRecord); + + updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + for (int i = 0; i < tokens.length(); i++) + Files.deleteIfExists(Paths.get(TOKENS_PATH + tokens.get(i))); + + // Populating data to explorer + // if (!EXPLORER_IP.contains("127.0.0.1")) { + // startTime = System.currentTimeMillis(); + // List tokenList = new ArrayList<>(); + // for (int i = 0; i < tokens.length(); i++) + // tokenList.add(tokens.getString(i)); + // String url = EXPLORER_IP + "/CreateOrUpdateRubixTransaction"; + // URL obj = new URL(url); + // HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); + + // // Setting basic post request + // con.setRequestMethod("POST"); + // con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); + // con.setRequestProperty("Accept", "application/json"); + // con.setRequestProperty("Content-Type", "application/json"); + // con.setRequestProperty("Authorization", "null"); + + // // Serialization + // JSONObject dataToSend = new JSONObject(); + // dataToSend.put("transaction_id", tid); + // dataToSend.put("sender_did", senderDidIpfsHash); + // dataToSend.put("receiver_did", receiverDidIpfsHash); + // dataToSend.put("token_id", tokenList); + // dataToSend.put("token_time", (int) totalTime); + // dataToSend.put("amount", amount); + // String populate = dataToSend.toString(); + + // JSONObject jsonObject = new JSONObject(); + // jsonObject.put("inputString", populate); + // String postJsonData = jsonObject.toString(); + + // // Send post request + // con.setDoOutput(true); + // DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + // wr.writeBytes(postJsonData); + // wr.flush(); + // wr.close(); + + // int responseCode = con.getResponseCode(); + // TokenSenderLogger.debug("Sending 'POST' request to URL : " + url); + // TokenSenderLogger.debug("Post Data : " + postJsonData); + // TokenSenderLogger.debug("Response Code : " + responseCode); + + // BufferedReader in = new BufferedReader( + // new InputStreamReader(con.getInputStream())); + // String output; + // StringBuffer response = new StringBuffer(); + + // while ((output = in.readLine()) != null) { + // response.append(output); + // } + // in.close(); + + // endTime = System.currentTimeMillis(); + // TokenSenderLogger.debug(response.toString()); + // } + + // + // if (type==1) { + // String urlQuorumUpdate = SYNC_IP+"/updateQuorum"; + // URL objQuorumUpdate = new URL(urlQuorumUpdate); + // HttpURLConnection conQuorumUpdate = (HttpURLConnection) + // objQuorumUpdate.openConnection(); + // + // conQuorumUpdate.setRequestMethod("POST"); + // conQuorumUpdate.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); + // conQuorumUpdate.setRequestProperty("Accept", "application/json"); + // conQuorumUpdate.setRequestProperty("Content-Type", "application/json"); + // conQuorumUpdate.setRequestProperty("Authorization", "null"); + // + // JSONObject dataToSendQuorumUpdate = new JSONObject(); + // dataToSendQuorumUpdate.put("completequorum", quorumArray); + // dataToSendQuorumUpdate.put("signedquorum",signedQuorumList); + // String populateQuorumUpdate = dataToSendQuorumUpdate.toString(); + // + // conQuorumUpdate.setDoOutput(true); + // DataOutputStream wrQuorumUpdate = new + // DataOutputStream(conQuorumUpdate.getOutputStream()); + // wrQuorumUpdate.writeBytes(populateQuorumUpdate); + // wrQuorumUpdate.flush(); + // wrQuorumUpdate.close(); + // + // int responseCodeQuorumUpdate = conQuorumUpdate.getResponseCode(); + // TokenSenderLogger.debug("Sending 'POST' request to URL : " + + // urlQuorumUpdate); + // TokenSenderLogger.debug("Post Data : " + populateQuorumUpdate); + // TokenSenderLogger.debug("Response Code : " + responseCodeQuorumUpdate); + // + // BufferedReader inQuorumUpdate = new BufferedReader( + // new InputStreamReader(conQuorumUpdate.getInputStream())); + // String outputQuorumUpdate; + // StringBuffer responseQuorumUpdate = new StringBuffer(); + // while ((outputQuorumUpdate = inQuorumUpdate.readLine()) != null) { + // responseQuorumUpdate.append(outputQuorumUpdate); + // } + // inQuorumUpdate.close(); + // + // } + + TokenSenderLogger.info("Transaction (DATA) Successful"); + // System.out.println("Verify Count: " + Authenticate.verifyCount); + // Authenticate.verifyCount = 0; + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); output.close(); input.close(); senderSocket.close(); - senderMutex = false; - updateQuorum(quorumArray, null, false, type); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", tid); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Receiver process not over"); - TokenSenderLogger.info("Incomplete Transaction"); - return APIResponse; - - } - - Iterator keys = InitiatorConsensus.quorumSignature.keys(); - JSONArray signedQuorumList = new JSONArray(); - while (keys.hasNext()) - signedQuorumList.put(keys.next()); - APIResponse.put("tid", tid); - APIResponse.put("status", "Success"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("message", "Tokens transferred successfully!"); - APIResponse.put("quorumlist", signedQuorumList); - APIResponse.put("receiver", receiverDidIpfsHash); - APIResponse.put("totaltime", totalTime); - - updateQuorum(quorumArray, signedQuorumList, true, type); - - JSONObject transactionRecord = new JSONObject(); - transactionRecord.put("role", "Sender"); - transactionRecord.put("tokens", tokens); - transactionRecord.put("txn", tid); - transactionRecord.put("quorumList", signedQuorumList); - transactionRecord.put("senderDID", senderDidIpfsHash); - transactionRecord.put("receiverDID", receiverDidIpfsHash); - transactionRecord.put("Date", getCurrentUtcTime()); - transactionRecord.put("totalTime", totalTime); - transactionRecord.put("comment", comment); - transactionRecord.put("essentialShare", InitiatorProcedure.essential); - - - JSONArray transactionHistoryEntry = new JSONArray(); - transactionHistoryEntry.put(transactionRecord); - updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); - - for (int i = 0; i < tokens.length(); i++) - Files.deleteIfExists(Paths.get(TOKENS_PATH + tokens.get(i))); - - - //Populating data to explorer - if (!EXPLORER_IP.contains("127.0.0.1")) { - List tokenList = new ArrayList<>(); - for (int i = 0; i < tokens.length(); i++) - tokenList.add(tokens.getString(i)); - String url = EXPLORER_IP + "/CreateOrUpdateRubixTransaction"; - URL obj = new URL(url); - HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); - - // Setting basic post request - con.setRequestMethod("POST"); - con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); - con.setRequestProperty("Accept", "application/json"); - con.setRequestProperty("Content-Type", "application/json"); - con.setRequestProperty("Authorization", "null"); - - // Serialization - JSONObject dataToSend = new JSONObject(); - dataToSend.put("transaction_id", tid); - dataToSend.put("sender_did", senderDidIpfsHash); - dataToSend.put("receiver_did", receiverDidIpfsHash); - dataToSend.put("token_id", tokenList); - dataToSend.put("token_time", (int) totalTime); - dataToSend.put("amount", amount); - String populate = dataToSend.toString(); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("inputString", populate); - String postJsonData = jsonObject.toString(); - - // Send post request - con.setDoOutput(true); - DataOutputStream wr = new DataOutputStream(con.getOutputStream()); - wr.writeBytes(postJsonData); - wr.flush(); - wr.close(); - - int responseCode = con.getResponseCode(); - TokenSenderLogger.debug("Sending 'POST' request to URL : " + url); - TokenSenderLogger.debug("Post Data : " + postJsonData); - TokenSenderLogger.debug("Response Code : " + responseCode); - - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String output; - StringBuffer response = new StringBuffer(); - - while ((output = in.readLine()) != null) { - response.append(output); - } - in.close(); - TokenSenderLogger.debug(response.toString()); } -// -// if (type==1) { -// String urlQuorumUpdate = SYNC_IP+"/updateQuorum"; -// URL objQuorumUpdate = new URL(urlQuorumUpdate); -// HttpURLConnection conQuorumUpdate = (HttpURLConnection) objQuorumUpdate.openConnection(); -// -// conQuorumUpdate.setRequestMethod("POST"); -// conQuorumUpdate.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); -// conQuorumUpdate.setRequestProperty("Accept", "application/json"); -// conQuorumUpdate.setRequestProperty("Content-Type", "application/json"); -// conQuorumUpdate.setRequestProperty("Authorization", "null"); -// -// JSONObject dataToSendQuorumUpdate = new JSONObject(); -// dataToSendQuorumUpdate.put("completequorum", quorumArray); -// dataToSendQuorumUpdate.put("signedquorum",signedQuorumList); -// String populateQuorumUpdate = dataToSendQuorumUpdate.toString(); -// -// conQuorumUpdate.setDoOutput(true); -// DataOutputStream wrQuorumUpdate = new DataOutputStream(conQuorumUpdate.getOutputStream()); -// wrQuorumUpdate.writeBytes(populateQuorumUpdate); -// wrQuorumUpdate.flush(); -// wrQuorumUpdate.close(); -// -// int responseCodeQuorumUpdate = conQuorumUpdate.getResponseCode(); -// TokenSenderLogger.debug("Sending 'POST' request to URL : " + urlQuorumUpdate); -// TokenSenderLogger.debug("Post Data : " + populateQuorumUpdate); -// TokenSenderLogger.debug("Response Code : " + responseCodeQuorumUpdate); -// -// BufferedReader inQuorumUpdate = new BufferedReader( -// new InputStreamReader(conQuorumUpdate.getInputStream())); -// String outputQuorumUpdate; -// StringBuffer responseQuorumUpdate = new StringBuffer(); -// while ((outputQuorumUpdate = inQuorumUpdate.readLine()) != null) { -// responseQuorumUpdate.append(outputQuorumUpdate); -// } -// inQuorumUpdate.close(); -// -// } - - TokenSenderLogger.info("Transaction Successful"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - output.close(); - input.close(); - senderSocket.close(); senderMutex = false; return APIResponse;