From 2ce49d144e9ab4db66b2cd7de74db0486e2fe300 Mon Sep 17 00:00:00 2001 From: n1dhn Date: Sun, 12 Dec 2021 13:19:57 +0530 Subject: [PATCH 01/11] + API handler for block commit + commit procedure + quorum pinning block hash file + qorum pinning files inside block hash file + block sender for committing node Signed-off-by: n1dhn --- .../rubix/Constants/ConsensusConstants.java | 4 + .../DataConsensus/BlockCommitInitiator.java | 263 +++++++ .../DataConsensus/BlockCommitProcedure.java | 140 ++++ .../DataConsensus/BlockCommitQuorum.java | 277 ++++++++ src/com/rubix/Resources/APIHandler.java | 131 ++-- src/com/rubix/TokenTransfer/BlockSender.java | 639 ++++++++++++++++++ 6 files changed, 1405 insertions(+), 49 deletions(-) create mode 100644 src/com/rubix/DataConsensus/BlockCommitInitiator.java create mode 100644 src/com/rubix/DataConsensus/BlockCommitProcedure.java create mode 100644 src/com/rubix/DataConsensus/BlockCommitQuorum.java create mode 100644 src/com/rubix/TokenTransfer/BlockSender.java diff --git a/src/com/rubix/Constants/ConsensusConstants.java b/src/com/rubix/Constants/ConsensusConstants.java index b67e588c..b4758108 100644 --- a/src/com/rubix/Constants/ConsensusConstants.java +++ b/src/com/rubix/Constants/ConsensusConstants.java @@ -6,6 +6,10 @@ 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 BLOCK = "BLOCK_HASH"; + public static final String TYPE = "CONSENSUS_TYPE"; + public static final String RBT = "RBT"; + public static final String RBD = "DATA_VALIDATION"; } diff --git a/src/com/rubix/DataConsensus/BlockCommitInitiator.java b/src/com/rubix/DataConsensus/BlockCommitInitiator.java new file mode 100644 index 00000000..d27746ff --- /dev/null +++ b/src/com/rubix/DataConsensus/BlockCommitInitiator.java @@ -0,0 +1,263 @@ +package com.rubix.DataConsensus; + +import static com.rubix.Resources.Functions.DATA_PATH; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.QUORUM_COUNT; +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.IPFSNetwork.forward; +import static com.rubix.Resources.IPFSNetwork.repo; +import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.Socket; +import java.util.ArrayList; + +import com.rubix.AuthenticateNode.Authenticate; +import com.rubix.Resources.IPFSNetwork; + +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; + +public class BlockCommitInitiator { + + public static Logger BlockCommitInitiatorLogger = Logger.getLogger(BlockCommitInitiator.class); + + public static volatile JSONObject quorumSignature = new JSONObject(); + private static final Object countLock = new Object(); + private static final Object signLock = new Object(); + public static ArrayList quorumWithShares = new ArrayList<>(); + public static volatile int[] quorumResponse = { 0, 0, 0 }; + public static volatile JSONArray finalQuorumSignsArray = new JSONArray(); + + /** + * This method increments the quorumResponse variable + */ + private static synchronized boolean voteNCount(int i, int quorumSize) { + boolean status; + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + synchronized (countLock) { + if (quorumResponse[i] < minQuorum(quorumSize)) { + quorumResponse[i]++; + BlockCommitInitiatorLogger.debug("quorum response added index " + i + " is " + quorumResponse[i] + + " quorumsize " + minQuorum(quorumSize)); + status = true; + } else { + status = false; + BlockCommitInitiatorLogger.debug("Consensus Reached for index " + i); + } + } + return status; + } + + /** + * 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) { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + synchronized (signLock) { + try { + if (quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7)) + && quorumResponse[index] <= minQuorum(quorumSize)) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("did", quorumDID); + jsonObject.put("sign", quorumSignResponse); + jsonObject.put("hash", hash); + finalQuorumSignsArray.put(jsonObject); + quorumSignature.put(quorumDID, quorumSignResponse); + } else { + BlockCommitInitiatorLogger.debug("quorum already reached consensus " + quorumSignature.length()); + } + } catch (JSONException e) { + BlockCommitInitiatorLogger.error("JSON Exception Occurred", e); + e.printStackTrace(); + } + } + } + + /** + * This method runs the consensus + * 1. Contact quorum with sender signatures and details + * 2. Verify quorum signatures + * 3. If consensus reached , sends shares to Quorum + * + * @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 { + String[] qResponse = 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]; + String[] quorumID = new String[QUORUM_COUNT]; + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + JSONObject dataObject = new JSONObject(data); + String hash = dataObject.getString("hash"); + JSONArray details = dataObject.getJSONArray("details"); + quorumResponse[index] = 0; + JSONArray tokenDetails; + try { + tokenDetails = new JSONArray(details.toString()); + JSONObject detailsToken = tokenDetails.getJSONObject(0); + JSONObject sharesToken = tokenDetails.getJSONObject(1); + + String[] shares = new String[minQuorum(7) - 1]; + for (int i = 0; i < shares.length; i++) { + int p = i + 1; + shares[i] = sharesToken.getString("Share" + p); + } + + for (int j = 0; j < quorumPeersObject.length(); j++) + quorumID[j] = quorumPeersObject.getString(j); + + Thread[] quorumThreads = new Thread[quorumPeersObject.length()]; + for (int i = 0; i < quorumPeersObject.length(); i++) { + int j = i; + quorumThreads[i] = new Thread(() -> { + + 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]); + nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); + String appName = quorumID[j].concat(role); + forward(appName, PORT + j, quorumID[j]); + BlockCommitInitiatorLogger.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") { + // BlockCommitInitiatorLogger.warn("Alpha quorum (" + quorumID[j] + ") has no + // credits"); + // } + // if (cmContent.length() == 0 && role == "alpha") { + // BlockCommitInitiatorLogger.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()))) + BlockCommitInitiatorLogger.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)) { + BlockCommitInitiatorLogger.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 { + BlockCommitInitiatorLogger.debug("Signature Received from " + quorumID[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]); + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", didHash); + detailsToVerify.put("hash", hash); + detailsToVerify.put("signature", qResponse[j]); + if (Authenticate.verifySignature(detailsToVerify.toString())) { + boolean voteStatus = voteNCount(index, quorumSize); + if (quorumResponse[index] <= minQuorum(quorumSize) && voteStatus) { + while (quorumResponse[index] < minQuorum(quorumSize)) { + } + 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); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); + } else { + + qOut[j].println("null"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); + } + BlockCommitInitiatorLogger.debug("Quorum Count : " + quorumResponse + + "Signature count : " + quorumSignature.length()); + } else { + BlockCommitInitiatorLogger.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]); + } + } + } + } catch (IOException | JSONException e) { + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); + BlockCommitInitiatorLogger.error("IOException Occurred"); + e.printStackTrace(); + } + }); + quorumThreads[j].start(); + } + + while (quorumResponse[index] < minQuorum(quorumSize) + || quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { + } + repo(ipfs); + + } catch (JSONException e) { + BlockCommitInitiatorLogger.error("JSON Exception Occurred", e); + e.printStackTrace(); + } + return quorumSignature; + } +} diff --git a/src/com/rubix/DataConsensus/BlockCommitProcedure.java b/src/com/rubix/DataConsensus/BlockCommitProcedure.java new file mode 100644 index 00000000..dbf0ad5c --- /dev/null +++ b/src/com/rubix/DataConsensus/BlockCommitProcedure.java @@ -0,0 +1,140 @@ +package com.rubix.DataConsensus; + +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 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; + +public class BlockCommitProcedure { + public static String essential; + public static String senderSignQ; + public static JSONObject payload = new JSONObject(); + public static JSONObject alphaReply, betaReply, gammaReply; + + public static Logger BlockCommitProcedureLogger = Logger.getLogger(BlockCommitProcedure.class); + + /** + * 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 { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + JSONObject dataObject = new JSONObject(data); + String tid = dataObject.getString("tid"); + String message = dataObject.getString("message"); + String blockHash = dataObject.getString("blockHash"); + 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(blockHash), "SHA3-256"); + + try { + payload.put("sender", senderDidIpfs); + // payload.put("token", token); + payload.put("blockHash", blockHash); + payload.put("tid", tid); + } catch (JSONException e) { + BlockCommitProcedureLogger.error("JSON Exception occurred", e); + e.printStackTrace(); + } + + Split.split(payload.toString()); + + int[][] shares = Split.get135Shares(); + BlockCommitProcedureLogger.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.TYPE, ConsensusConstants.RBD); + data1.put(ConsensusConstants.BLOCK, blockHash); + + data2.put("Share1", Q1Share); + data2.put("Share2", Q2Share); + data2.put("Share3", Q3Share); + data2.put("Share4", Q4Share); + } catch (JSONException | IOException e) { + BlockCommitProcedureLogger.error("JSON Exception occurred", e); + e.printStackTrace(); + } + + JSONArray detailsForQuorum = new JSONArray(); + detailsForQuorum.put(data1); + detailsForQuorum.put(data2); + + BlockCommitProcedureLogger.debug("Invoking Consensus"); + + JSONObject dataSend = new JSONObject(); + dataSend.put("hash", authQuorumHash); + dataSend.put("details", detailsForQuorum); + + Thread alphaThread = new Thread(() -> { + try { + alphaReply = BlockCommitInitiator.start(dataSend.toString(), ipfs, PORT, 0, "alpha", alphaList, alphaSize, + alphaSize); + } catch (JSONException e) { + e.printStackTrace(); + } + }); + + Thread betaThread = new Thread(() -> { + try { + betaReply = BlockCommitInitiator.start(dataSend.toString(), ipfs, PORT + 100, 1, "beta", betaList, + alphaSize, 7); + } catch (JSONException e) { + e.printStackTrace(); + } + }); + + Thread gammaThread = new Thread(() -> { + try { + gammaReply = BlockCommitInitiator.start(dataSend.toString(), ipfs, PORT + 107, 2, "gamma", gammaList, + alphaSize, 7); + } catch (JSONException e) { + e.printStackTrace(); + } + }); + + BlockCommitInitiator.quorumSignature = new JSONObject(); + alphaThread.start(); + betaThread.start(); + gammaThread.start(); + while (BlockCommitInitiator.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { + } + BlockCommitProcedureLogger + .debug("ABG Consensus completed with length " + BlockCommitInitiator.quorumSignature.length()); + } +} diff --git a/src/com/rubix/DataConsensus/BlockCommitQuorum.java b/src/com/rubix/DataConsensus/BlockCommitQuorum.java new file mode 100644 index 00000000..74e9615e --- /dev/null +++ b/src/com/rubix/DataConsensus/BlockCommitQuorum.java @@ -0,0 +1,277 @@ +package com.rubix.DataConsensus; + +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.readFile; +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.listen; + +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.Constants.ConsensusConstants; +import com.rubix.Resources.IPFSNetwork; + +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; + +public class BlockCommitQuorum implements Runnable { + + public static Logger BlockCommitQuorumLogger = Logger.getLogger(BlockCommitQuorum.class); + + /** + * This method is used to run a thread for Quorum Members + *

+ * This involves + *

    + *
  1. Verify sender signature
  2. + *
  3. Signing the transaction
  4. + *
  5. Receiving share from sender
  6. + *
+ */ + + int port; + IPFS ipfs; + String role; + int round; + + public BlockCommitQuorum(String role, int port) { + this.role = role; + this.port = 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, blockHash, receiverPID, appName, senderPrivatePos, + senderDidIpfsHash = "", senderPID = ""; + ServerSocket serverSocket = null; + Socket socket = null; + try { + + peerID = getPeerID(DATA_PATH + "DID.json"); + String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID); + appName = peerID.concat(role); + + listen(appName, port); + + BlockCommitQuorumLogger.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 + + qstReq = dataReq.readLine(); + if (qstReq.contains("qstcmrequest")) { + + BlockCommitQuorumLogger + .debug("Sender reqesting QuorumSignedTransactions.json and CreditMapping.json: " + qstReq); + + File creditsMapping = new File(WALLET_DATA_PATH + "CreditMapping.json"); + if (!creditsMapping.exists()) { + BlockCommitQuorumLogger.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); + + String cmFileHash = IPFSNetwork.add(WALLET_DATA_PATH + "CreditMapping.json", ipfs); + + JSONObject qResponse = new JSONObject(); + qResponse.put("QuorumSignedTransactions", qstObjectSend.toString()); + qResponse.put("CreditMapping", cmFileHash); + + dataResp.println(qResponse.toString()); + } + + // TODO: if the incoming request contains the keyword "request", push the QST to + // IPFS and send the two hashes back to the sender. + + // ? This is where quorum fetched the data send from initiatorConsensus (Line + // 148) + + getData = in.readLine(); + if (getData.contains("ping check")) { + BlockCommitQuorumLogger.debug("Ping check from sender: " + getData); + out.println("pong response"); + } else { + BlockCommitQuorumLogger.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"); + blockHash = readSenderData.getString(ConsensusConstants.BLOCK); + + senderPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", senderDidIpfsHash); + // receiverPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", blockHash); + + String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", + senderDidIpfsHash); + + nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); + String quorumHash = calculateHash(verifySenderHash.concat(blockHash), "SHA3-256"); + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", senderDidIpfsHash); + detailsToVerify.put("hash", verifySenderHash); + detailsToVerify.put("signature", senderPrivatePos); + + // BlockCommitQuorumLogger.debug("Checking providers for: " + verifySenderHash); + // ArrayList dhtOwnersList = dhtOwnerCheck(verifySenderHash); + // BlockCommitQuorumLogger.debug("Providers: " + dhtOwnersList); + // boolean consensusIDcheck = true; + // 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"); + + //TODO: check minimum balance of sender is one RBT + + //TODO: verifying the block hash, fetching block hash and pinning files in block file. + if (Authenticate.verifySignature(detailsToVerify.toString())) { + BlockCommitQuorumLogger.debug("Quorum Authenticated Sender"); + + IPFSNetwork.pin(blockHash, ipfs); + + pinBlockFiles(blockHash, ipfs); + String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + quorumHash); + out.println(QuorumSignature); + String creditval; + creditval = in.readLine(); + BlockCommitQuorumLogger.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); + + } + + JSONObject storeDetailsQuorum = new JSONObject(); + storeDetailsQuorum.put("tid", transactionID); + storeDetailsQuorum.put("consensusID", verifySenderHash); + storeDetailsQuorum.put("sign", senderPrivatePos); + storeDetailsQuorum.put("credits", credit); + storeDetailsQuorum.put("senderdid", senderDidIpfsHash); + + //? During mining if QST file has blockHash instead of recieverID, then credit is counted as 2 for that transaction. + storeDetailsQuorum.put("blockHash", blockHash); + + JSONArray data = new JSONArray(); + data.put(storeDetailsQuorum); + BlockCommitQuorumLogger.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"); + BlockCommitQuorumLogger.debug("added consensus ID " + consenusIDhash); + } + } else { + BlockCommitQuorumLogger.debug("Sender Authentication Failure - Quorum"); + out.println("Auth_Failed"); + } + } + } catch (IOException e) { + BlockCommitQuorumLogger.error("IOException Occurred", e); + } catch (JSONException e) { + BlockCommitQuorumLogger.error("JSONException Occurred", e); + } catch (NullPointerException e) { + BlockCommitQuorumLogger.error("NullPointer Exception Occurred ", e); + } + + finally { + try { + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } catch (IOException e) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + BlockCommitQuorumLogger.error("IOException Occurred", e); + } + + } + } + + } + + private void pinBlockFiles(String blockHash, IPFS ipfs) throws JSONException { + 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); + } + + } +} diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 6563a971..7c518903 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -1,10 +1,19 @@ 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.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.executeIPFSCommands; + import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -14,10 +23,25 @@ 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 com.rubix.TokenTransfer.BlockSender; +import com.rubix.TokenTransfer.ProofCredits; +import com.rubix.TokenTransfer.TokenSender; -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +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); @@ -42,58 +66,67 @@ public static JSONObject send(String data) throws Exception { 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 UserResponse = 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; + dataObject.put("pvt", DATA_PATH + senDID + "/PrivateShare.png"); + + if(dataObject.has("receiverDidIpfsHash")) { + + String recDID = dataObject.getString("receiverDidIpfsHash"); + + 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; + } + } + if(!isObjectValid) + networkInfo(); + + if (recDID.length() != 46) { + UserResponse.put("did", senDID); + UserResponse.put("tid", "null"); + UserResponse.put("status", "Failed"); + UserResponse.put("message", "Invalid Receiver Did Entered"); + return UserResponse; } - } - if(!isObjectValid) - networkInfo(); -// String comments = dataObject.getString("comments"); - JSONArray tokens = dataObject.getJSONArray("tokens"); -// JSONArray tokenHeader = dataObject.getJSONArray("tokenHeader"); -// int amount = dataObject.getInt("amount"); + // String comments = dataObject.getString("comments"); + JSONArray tokens = dataObject.getJSONArray("tokens"); + // JSONArray tokenHeader = dataObject.getJSONArray("tokenHeader"); + // int amount = dataObject.getInt("amount"); + + if (tokens.length() < 1) { + UserResponse.put("did", senDID); + UserResponse.put("tid", "null"); + UserResponse.put("status", "Failed"); + UserResponse.put("message", "Invalid amount"); + return UserResponse; + } + // 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); + UserResponse = TokenSender.Send(dataObject.toString(), ipfs, SEND_PORT); - 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; + // sendMessage = TokenSender.Send(detailsObject.toString(), ipfs, SEND_PORT); } - if (tokens.length() < 1) { - sendMessage.put("did", senDID); - sendMessage.put("tid", "null"); - sendMessage.put("status", "Failed"); - sendMessage.put("message", "Invalid amount"); - return sendMessage; + if(dataObject.has("blockHash")) { + UserResponse = BlockSender.Send(dataObject.toString(), ipfs, SEND_PORT); } -// 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); -// sendMessage = TokenSender.Send(detailsObject.toString(), ipfs, SEND_PORT); - APILogger.info(sendMessage); - return sendMessage; + APILogger.info(UserResponse); + return UserResponse; } diff --git a/src/com/rubix/TokenTransfer/BlockSender.java b/src/com/rubix/TokenTransfer/BlockSender.java new file mode 100644 index 00000000..f271cda7 --- /dev/null +++ b/src/com/rubix/TokenTransfer/BlockSender.java @@ -0,0 +1,639 @@ +package com.rubix.TokenTransfer; + +import static com.rubix.Resources.Functions.DATA_PATH; +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.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.readFile; +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.repo; + +import java.awt.image.BufferedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.Socket; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Iterator; + +import javax.imageio.ImageIO; + +import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Consensus.InitiatorConsensus; +import com.rubix.Consensus.InitiatorProcedure; +import com.rubix.Resources.IPFSNetwork; + +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; + +public class BlockSender { + private static final Logger BlockSenderLogger = Logger.getLogger(BlockSender.class); + 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; + + /** + * A sender node to transfer tokens + * + * @param data Details required for tokenTransfer + * @param ipfs IPFS instance + * @param port Sender port for communication + * @return Transaction Details (JSONObject) + * @throws IOException handles IO Exceptions + * @throws JSONException handles JSON Exceptions + * @throws NoSuchAlgorithmException handles No Such Algorithm Exceptions + */ + 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 blockHash = detailsObject.getString("blockHash"); + 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(); + JSONArray gammaQuorum = new JSONArray(); + int heartBeatAlpha = 0; + int heartBeatBeta = 0; + int heartBeatGamma = 0; + int alphaSize; + + ArrayList alphaPeersList; + ArrayList betaPeersList; + ArrayList gammaPeersList; + + String senderPeerID = getPeerID(DATA_PATH + "DID.json"); + BlockSenderLogger.debug("sender peer id" + senderPeerID); + String senderDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", senderPeerID); + BlockSenderLogger.debug("sender did ipfs hash" + senderDidIpfsHash); + BlockSenderLogger.debug("path is" + DATA_PATH + senderDidIpfsHash); + File folder = new File(DATA_PATH + senderDidIpfsHash); + File[] listOfFiles = folder.listFiles(); + + //? Need more details! + 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); + + if (senderMutex) { + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender busy. Try again later"); + BlockSenderLogger.warn("Sender busy"); + return APIResponse; + } + + senderMutex = true; + + String peerAuth; + // ArrayList allTokensChainsPushed = new ArrayList(); + APIResponse = new JSONObject(); + + // if (tokens.length() == 0) { + + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", "null"); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "No balance"); + // senderMutex = false; + // return APIResponse; + // } + + // 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"); + // BlockSenderLogger.debug(token + "and " + tokenchain); + // if (!(token.exists() && tokenchain.exists())) { + // BlockSenderLogger.info("Tokens Not Verified"); + // senderMutex = false; + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", "null"); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Invalid token(s)"); + // return APIResponse; + + // } + // add(TOKENS_PATH + tokens.get(i), ipfs); + // String tokenChainHash = add(TOKENCHAIN_PATH + tokens.get(i) + ".json", ipfs); + // allTokensChainsPushed.add(tokenChainHash); + // } + + String authSenderByRecHash = calculateHash( + blockHash + comment, "SHA3-256"); + String tid = calculateHash(authSenderByRecHash + comment, "SHA3-256"); + BlockSenderLogger.debug("Sender by Receiver Hash " + authSenderByRecHash); + BlockSenderLogger.debug("TID on sender " + tid); + + 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(senderDidIpfsHash), false); + String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); + deleteFile(LOGGER_PATH + "tempgamma"); + + switch (type) { + case 1: { + quorumArray = getQuorum(betaHash, gammaHash, senderDidIpfsHash, senderDidIpfsHash, 1); + break; + } + + case 2: { + quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + break; + } + case 3: { + quorumArray = detailsObject.getJSONArray("quorum"); + break; + } + default: { + BlockSenderLogger.error("Unknown quorum type input, cancelling transaction"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Unknown quorum type input, cancelling transaction"); + return APIResponse; + + } + } + + QuorumSwarmConnect(quorumArray, ipfs); + + 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)); + } + + BlockSenderLogger.debug("alphaquorum " + alphaQuorum + " size " + alphaQuorum.length()); + BlockSenderLogger.debug("betaquorum " + betaQuorum + " size " + betaQuorum.length()); + BlockSenderLogger.debug("gammaquorum " + gammaQuorum + " size " + gammaQuorum.length()); + + alphaPeersList = QuorumCheck(alphaQuorum, alphaSize); + betaPeersList = QuorumCheck(betaQuorum, 7); + gammaPeersList = QuorumCheck(gammaQuorum, 7); + + // for(int i=0;i= minQuorum(7))) { + BlockSenderLogger.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; + + } + + // BlockSenderLogger.debug("Consensus Reached"); + // senderDetails2Receiver.put("status", "Consensus Reached"); + // senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); + + // output.println(senderDetails2Receiver); + // output.println("Consensus Reached"); + BlockSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); + // output.println(InitiatorConsensus.quorumSignature); + + String signatureAuth = input.readLine(); + + long endAuth = System.currentTimeMillis(); + long totalTime = endAuth - startTime; + if (!signatureAuth.equals("200")) { + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + BlockSenderLogger.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); + + // BlockSenderLogger.debug("Unpinned Tokens"); + // output.println("Unpinned"); + + // String confirmation = input.readLine(); + // if (!confirmation.equals("Successfully Pinned")) { + // BlockSenderLogger.warn("Multiple Owners for the token"); + // // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + // BlockSenderLogger.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", "Receiver process not over"); + BlockSenderLogger.info("Incomplete Transaction"); + return APIResponse; + + } + + //? below code is verified for block sender logic + + 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", "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()); + + // 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("blockHash", blockHash); + // 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(); + // BlockSenderLogger.debug("Sending 'POST' request to URL : " + url); + // BlockSenderLogger.debug("Post Data : " + postJsonData); + // BlockSenderLogger.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(); + + // BlockSenderLogger.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(); + // BlockSenderLogger.debug("Sending 'POST' request to URL : " + + // urlQuorumUpdate); + // BlockSenderLogger.debug("Post Data : " + populateQuorumUpdate); + // BlockSenderLogger.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(); + // + // } + + BlockSenderLogger.info("Transaction Successful"); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; + return APIResponse; + + } +} From 876521d0e5a44ed09b3b4b71c0c2c94a40e2e5e1 Mon Sep 17 00:00:00 2001 From: n1dhn Date: Tue, 14 Dec 2021 19:27:02 +0530 Subject: [PATCH 02/11] function to count pins on each metadata hash Signed-off-by: n1dhn --- .../rubix/Consensus/InitiatorConsensus.java | 19 +++++++++++++++++++ src/com/rubix/Resources/APIHandler.java | 4 +--- src/com/rubix/Resources/Functions.java | 1 - 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 0babc9cc..9611e773 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -6,6 +6,7 @@ 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.IPFSNetwork.dhtOwnerCheck; import static com.rubix.Resources.IPFSNetwork.forward; import static com.rubix.Resources.IPFSNetwork.repo; import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; @@ -88,6 +89,24 @@ private static synchronized void quorumSign(String quorumDID, String hash, Strin } } + public static JSONObject countQuorumSigns(String blockObject) throws JSONException, InterruptedException, IOException { + + // convert blockHash to a JSONObject + JSONObject response = new JSONObject(); + + // convert blockObject string to json object + JSONObject blockObjectJson = new JSONObject(blockObject); + JSONArray metadataArray = blockObjectJson.getJSONArray("metadata"); + + for (int i = 0; i < metadataArray.length(); i++) { + JSONObject metadataObject = metadataArray.getJSONObject(i); + String metadata_hash = metadataObject.getString("metadata_hash"); + ArrayList dhtOwnersList = dhtOwnerCheck(metadata_hash); + response.put(metadata_hash, dhtOwnersList.size()); + } + return response; + } + /** * This method runs the consensus diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 7c518903..adc9bac1 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -421,7 +421,6 @@ 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 @@ -441,7 +440,6 @@ public static JSONArray transactionsByDID(String did) throws JSONException { return resultArray; } - public static int onlinePeersCount() throws JSONException, IOException, InterruptedException { JSONArray peersArray = peersOnlineStatus(); int count = 0; @@ -452,7 +450,6 @@ public static int onlinePeersCount() throws JSONException, IOException, Interrup return count; } - public static ArrayList swarmPeersList() throws IOException, InterruptedException { String OS = getOsName(); String[] command = new String[3]; @@ -489,6 +486,7 @@ else if(OS.contains("Windows")){ } return peersArray; } + /** * A call to get the online/offline status of your contacts * @return List indicating online status of each DID contact diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index b7331468..fdb903ec 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -136,7 +136,6 @@ public static void pathSet() { } } - //? public static void nodeData(String did, String wid, IPFS ipfs) throws IOException { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); From 6d7a0b606035659304af3b75cbd3071f3a549fad Mon Sep 17 00:00:00 2001 From: n1dhn Date: Tue, 14 Dec 2021 19:40:42 +0530 Subject: [PATCH 03/11] /verifyBlock response Signed-off-by: n1dhn --- src/com/rubix/Consensus/InitiatorConsensus.java | 6 ++++++ src/com/rubix/Resources/APIHandler.java | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 9611e773..afda3fbb 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -93,17 +93,23 @@ public static JSONObject countQuorumSigns(String blockObject) throws JSONExcepti // convert blockHash to a JSONObject JSONObject response = new JSONObject(); + response.put("blockHash", blockObject); // convert blockObject string to json object JSONObject blockObjectJson = new JSONObject(blockObject); JSONArray metadataArray = blockObjectJson.getJSONArray("metadata"); + response.put("files", metadataArray.length()); + for (int i = 0; i < metadataArray.length(); i++) { JSONObject metadataObject = metadataArray.getJSONObject(i); String metadata_hash = metadataObject.getString("metadata_hash"); ArrayList dhtOwnersList = dhtOwnerCheck(metadata_hash); response.put(metadata_hash, dhtOwnersList.size()); } + + response.put("status", "Success"); + return response; } diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index adc9bac1..f9d17c02 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -1,5 +1,6 @@ package com.rubix.Resources; +import static com.rubix.Consensus.InitiatorConsensus.countQuorumSigns; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; @@ -160,6 +161,10 @@ public static JSONObject create(int type) throws Exception { return sendMessage; } + public static JSONObject getBatchPins(String blockHash) throws Exception { + return countQuorumSigns(blockHash); + } + /** * A call to get details of a transaction given its ID From 3337fd227727d57c4bb08e522487656f3c093e31 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 15 Dec 2021 14:59:38 +0530 Subject: [PATCH 04/11] fix: blocksender validation Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/BlockSender.java | 52 ++++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/src/com/rubix/TokenTransfer/BlockSender.java b/src/com/rubix/TokenTransfer/BlockSender.java index f271cda7..55339afe 100644 --- a/src/com/rubix/TokenTransfer/BlockSender.java +++ b/src/com/rubix/TokenTransfer/BlockSender.java @@ -78,7 +78,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception JSONObject APIResponse = new JSONObject(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - String receiverPeerId; + // String receiverPeerId; JSONObject detailsObject = new JSONObject(data); // String receiverDidIpfsHash = detailsObject.getString("receiverDidIpfsHash"); String pvt = detailsObject.getString("pvt"); @@ -265,10 +265,10 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception // ? above code is verified for block sender logic - // JSONObject senderDetails2Receiver = new JSONObject(); - // senderDetails2Receiver.put("sign", senderSign); - // senderDetails2Receiver.put("tid", tid); - // senderDetails2Receiver.put("comment", comment); + JSONObject senderDetails2Receiver = new JSONObject(); + senderDetails2Receiver.put("sign", senderSign); + senderDetails2Receiver.put("tid", tid); + senderDetails2Receiver.put("comment", comment); // JSONArray tokenBindDetailsArray = new JSONArray(); // JSONObject tokenDetails = new JSONObject(); @@ -402,8 +402,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception if (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { // if (!(InitiatorProcedure.alphaReply.length() >= minQuorum(7))) { BlockSenderLogger.debug("Consensus Failed"); - // senderDetails2Receiver.put("status", "Consensus Failed"); - // senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); + senderDetails2Receiver.put("status", "Consensus Failed"); + senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); // output.println(senderDetails2Receiver); // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); output.close(); @@ -419,9 +419,9 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } - // BlockSenderLogger.debug("Consensus Reached"); - // senderDetails2Receiver.put("status", "Consensus Reached"); - // senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); + BlockSenderLogger.debug("Consensus Reached"); + senderDetails2Receiver.put("status", "Consensus Reached"); + senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); // output.println(senderDetails2Receiver); // output.println("Consensus Reached"); @@ -475,25 +475,25 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception // return APIResponse; // } - output.println(InitiatorProcedure.essential); - String respAuth = input.readLine(); + // output.println(InitiatorProcedure.essential); + // String respAuth = input.readLine(); - if (!respAuth.equals("Send Response")) { + // 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", "Receiver process not over"); - BlockSenderLogger.info("Incomplete Transaction"); - return APIResponse; + // // 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"); + // BlockSenderLogger.info("Incomplete Transaction"); + // return APIResponse; - } + // } //? below code is verified for block sender logic From a90d6cb724d82b356469ebfed81cbc9fbfb09a44 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 15 Dec 2021 17:58:31 +0530 Subject: [PATCH 05/11] updated with latest credit-security logic (epsilon-1-8) Signed-off-by: Nidhin Mahesh A --- .../rubix/AuthenticateNode/Authenticate.java | 4 +- .../rubix/Consensus/InitiatorConsensus.java | 102 +++++------ .../rubix/Consensus/InitiatorProcedure.java | 3 + src/com/rubix/Consensus/QuorumConsensus.java | 166 ++++++++++-------- .../rubix/Constants/ConsensusConstants.java | 1 - src/com/rubix/Resources/APIHandler.java | 1 - src/com/rubix/Resources/Functions.java | 72 ++------ src/com/rubix/Resources/IPFSNetwork.java | 10 +- .../rubix/TokenTransfer/TokenReceiver.java | 33 +--- src/com/rubix/TokenTransfer/TokenSender.java | 23 +-- 10 files changed, 186 insertions(+), 229 deletions(-) diff --git a/src/com/rubix/AuthenticateNode/Authenticate.java b/src/com/rubix/AuthenticateNode/Authenticate.java index c26a8b44..f5674dc3 100644 --- a/src/com/rubix/AuthenticateNode/Authenticate.java +++ b/src/com/rubix/AuthenticateNode/Authenticate.java @@ -16,6 +16,7 @@ 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. @@ -29,8 +30,8 @@ public class Authenticate { 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"); @@ -61,7 +62,6 @@ public static boolean verifySignature(String detailString) throws IOException, J StringBuilder decentralizedIDForAuth = new StringBuilder(); 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"); diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index afda3fbb..b92d55c2 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -89,13 +89,14 @@ private static synchronized void quorumSign(String quorumDID, String hash, Strin } } - public static JSONObject countQuorumSigns(String blockObject) throws JSONException, InterruptedException, IOException { + public static JSONObject countQuorumSigns(String blockObject) + throws JSONException, InterruptedException, IOException { // convert blockHash to a JSONObject JSONObject response = new JSONObject(); response.put("blockHash", blockObject); - // convert blockObject string to json object + // convert blockObject string to json object JSONObject blockObjectJson = new JSONObject(blockObject); JSONArray metadataArray = blockObjectJson.getJSONArray("metadata"); @@ -113,7 +114,6 @@ public static JSONObject countQuorumSigns(String blockObject) throws JSONExcepti return response; } - /** * This method runs the consensus * 1. Contact quorum with sender signatures and details @@ -135,6 +135,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()); @@ -142,7 +143,7 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri JSONObject sharesToken = tokenDetails.getJSONObject(1); String[] shares = new String[minQuorum(7) - 1]; - for (int i = 0; i < shares.length; i++) { + for(int i = 0; i < shares.length; i++){ int p = i + 1; shares[i] = sharesToken.getString("Share" + p); } @@ -156,22 +157,30 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri quorumThreads[i] = new Thread(() -> { try { - swarmConnectP2P(quorumID[j], ipfs); + 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]); nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); String appName = quorumID[j].concat(role); - forward(appName, PORT + j, quorumID[j]); - InitiatorConsensusLogger.debug("Connected to " + quorumID[j] + "on port " + (PORT + j) + "with AppName" + appName); - qSocket[j] = new Socket("127.0.0.1", PORT + j); + 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); + 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); + String data1 = quorumDetails.getString("CreditMapping"); + JSONArray cmContent = new JSONArray(data1); + - JSONObject qstContent = new JSONObject(quorumDetails.getString("QuorumSignedTransactions")); + String data2 = quorumDetails.getString("Credits"); + JSONArray creditsArray = new JSONArray(data2); + if(creditsArray.length() > 0) { + InitiatorConsensusLogger.debug("Entering Credits Security"); + }else + InitiatorConsensusLogger.debug("Old Credits file"); // if (qstContent.length() == 0 && role == "alpha") { @@ -181,48 +190,43 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri // 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"); + if(creditsArray.length() != 0) { + for (int k = 0; k < creditsArray.length(); k++) { + JSONObject object = creditsArray.getJSONObject(k); + String did = object.getString("did"); + String sign = object.getString("sign"); + String signHash = object.getString("hash"); - 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); - 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 (!(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"); - } + 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]); + } + else { + 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]); @@ -233,19 +237,21 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri detailsToVerify.put("hash", hash); detailsToVerify.put("signature", qResponse[j]); if (Authenticate.verifySignature(detailsToVerify.toString())) { - boolean voteStatus = voteNCount(index, quorumSize); + InitiatorConsensusLogger.debug(role + " node authenticated at index " + index); + boolean voteStatus = voteNCount(index,quorumSize); if (quorumResponse[index] <= minQuorum(quorumSize) && voteStatus) { - while (quorumResponse[index] < minQuorum(quorumSize)) { - } - quorumSign(didHash, hash, qResponse[j], index, quorumSize, alphaSize); + 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); + while (quorumSignature.length() < (minQuorum(alphaSize) + 2* minQuorum(7))) {} + 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 { - + } + else { + InitiatorConsensusLogger.debug("sending null for slow quorum "); qOut[j].println("null"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } @@ -265,10 +271,8 @@ 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..3e0372f6 100644 --- a/src/com/rubix/Consensus/InitiatorProcedure.java +++ b/src/com/rubix/Consensus/InitiatorProcedure.java @@ -44,6 +44,8 @@ public static void consensusSetUp(String data,IPFS ipfs, int PORT,int alphaSize) String authSenderByQuorumHash="", authQuorumHash=""; authSenderByQuorumHash = message; 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); @@ -120,6 +122,7 @@ public static void consensusSetUp(String data,IPFS ipfs, int PORT,int alphaSize) }); InitiatorConsensus.quorumSignature=new JSONObject(); + InitiatorConsensus.finalQuorumSignsArray = new JSONArray(); alphaThread.start(); betaThread.start(); gammaThread.start(); diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index e10ae9a3..b5e2964c 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -86,24 +86,30 @@ public void run() { writeToFile(creditsMapping.toString(), "[]", false); } JSONArray qstContent = new JSONArray(readFile(WALLET_DATA_PATH + "QuorumSignedTransactions.json")); - JSONObject qstObjectSend = new JSONObject(); - if(qstContent.length() > 0) + JSONObject qstObjectSend; + JSONArray creditsArray = new JSONArray(); + String credits = ""; + if(qstContent.length() > 0) { qstObjectSend = qstContent.getJSONObject(qstContent.length() - 1); + if(!qstObjectSend.has("minestatus")) { + QuorumConsensusLogger.debug("Entering Credits Security"); + credits = qstObjectSend.getString("credits"); + if (!credits.equals("")) { + String creditContent = IPFSNetwork.get(credits, ipfs); + creditsArray = new JSONArray(creditContent); + } + } + } - String cmFileHash = IPFSNetwork.add(WALLET_DATA_PATH + "CreditMapping.json", ipfs); - + String cmFile = readFile(WALLET_DATA_PATH + "CreditMapping.json"); + JSONArray creditsMappingArray = new JSONArray(cmFile); JSONObject qResponse = new JSONObject(); - qResponse.put("QuorumSignedTransactions", qstObjectSend.toString()); - qResponse.put("CreditMapping", cmFileHash); + qResponse.put("Credits", creditsArray.toString()); + qResponse.put("CreditMapping", creditsMappingArray.toString()); dataResp.println(qResponse.toString()); } - - //TODO: if the incoming request contains the keyword "request", push the QST to IPFS and send the two hashes back to the sender. - - //? This is where quorum fetched the data send from initiatorConsensus (Line 148) - getData = in.readLine(); if (getData.contains("ping check")) { QuorumConsensusLogger.debug("Ping check from sender: " + getData); @@ -132,71 +138,83 @@ public void run() { detailsToVerify.put("signature", senderPrivatePos); - 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"); +// 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 (Authenticate.verifySignature(detailsToVerify.toString()) && consensusIDcheck) { + if (Authenticate.verifySignature(detailsToVerify.toString())) { 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); - + if(!dhtEmpty(verifySenderHash, ipfs)) { + QuorumConsensusLogger.debug("ConsensusID pass"); + 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); + + } + 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 { + 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{ + QuorumConsensusLogger.debug("Sender Authentication Failure - ConsensusID"); + out.println("Auth_Failed"); } } else { QuorumConsensusLogger.debug("Sender Authentication Failure - Quorum"); @@ -207,7 +225,7 @@ public void run() { QuorumConsensusLogger.error("IOException Occurred", e); } catch (JSONException e) { QuorumConsensusLogger.error("JSONException Occurred", e); - } catch (NullPointerException | InterruptedException e) { + } catch (NullPointerException e) { QuorumConsensusLogger.error("NullPointer Exception Occurred ",e); } diff --git a/src/com/rubix/Constants/ConsensusConstants.java b/src/com/rubix/Constants/ConsensusConstants.java index b4758108..edcc1e82 100644 --- a/src/com/rubix/Constants/ConsensusConstants.java +++ b/src/com/rubix/Constants/ConsensusConstants.java @@ -11,5 +11,4 @@ public class ConsensusConstants { public static final String RBT = "RBT"; public static final String RBD = "DATA_VALIDATION"; - } diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index f9d17c02..a115425d 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -165,7 +165,6 @@ public static JSONObject getBatchPins(String blockHash) throws Exception { return countQuorumSigns(blockHash); } - /** * A call to get details of a transaction given its ID * @param txnId diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index fdb903ec..7f0021d6 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1,23 +1,14 @@ 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; -import static com.rubix.Resources.IPFSNetwork.listen; +import com.rubix.AuthenticateNode.PropImage; +import io.ipfs.api.*; +import org.apache.log4j.*; +import org.json.*; +import javax.imageio.ImageIO; import java.awt.image.BufferedImage; -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -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.io.*; +import java.net.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; @@ -25,21 +16,10 @@ import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; - -import javax.imageio.ImageIO; - -import com.rubix.AuthenticateNode.PropImage; - -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; +import java.util.*; -import io.ipfs.api.IPFS; +import static com.rubix.Resources.APIHandler.*; +import static com.rubix.Resources.IPFSNetwork.*; public class Functions { @@ -136,7 +116,7 @@ public static void pathSet() { } } - //? + 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 + "/"); @@ -220,7 +200,6 @@ public static String getSystemUser() { * @return (String) hash */ - //? rubix-crypto public static String calculateHash(String message, String algorithm) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); MessageDigest digest = null; @@ -561,6 +540,7 @@ public static ArrayList QuorumCheck(JSONArray quorum, int size) { 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); @@ -764,30 +744,9 @@ public static void deleteFile(String fileName) { 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"); } /** @@ -796,7 +755,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); @@ -1048,7 +1006,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; } diff --git a/src/com/rubix/Resources/IPFSNetwork.java b/src/com/rubix/Resources/IPFSNetwork.java index 72c894ea..b948580c 100644 --- a/src/com/rubix/Resources/IPFSNetwork.java +++ b/src/com/rubix/Resources/IPFSNetwork.java @@ -330,8 +330,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; } @@ -453,7 +453,7 @@ 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 +520,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,6 +554,8 @@ 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) { diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 05546232..975c35dd 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -20,9 +20,7 @@ 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 java.util.*; import static com.rubix.Resources.Functions.*; import static com.rubix.Resources.IPFSNetwork.*; @@ -110,14 +108,11 @@ public static String receive() { output.println("200"); String data = input.readLine(); - TokenReceiverLogger.debug("Token details received: " + data); + TokenReceiverLogger.debug("Token details received: "); 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); @@ -127,11 +122,6 @@ public static String receive() { String senderToken = TokenDetailsArray.getJSONObject(0).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"); - - //Check IPFS get for all Tokens int ipfsGetFlag = 0; @@ -159,8 +149,8 @@ public static String receive() { 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; + else if(IPFSNetwork.dhtEmpty(getCIDipfsHash, ipfs)){ + String errorMessage = "Consensus ID issue"; output.println("421"); APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); @@ -211,20 +201,16 @@ 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); 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()); Iterator keys = quorumSignatures.keys(); while (keys.hasNext()) { @@ -240,7 +226,6 @@ else if(!(ipfsGetFlag == tokenCount)){ 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"); } } @@ -269,8 +254,6 @@ 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); if (!(yesSender && yesQuorum)) { output.println("420"); APIResponse.put("did", senderDidIpfsHash); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index d95b8146..71694e1d 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -1,5 +1,6 @@ package com.rubix.TokenTransfer; +import com.rubix.AuthenticateNode.Authenticate; import com.rubix.AuthenticateNode.PropImage; import com.rubix.Consensus.InitiatorConsensus; @@ -103,9 +104,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } - BufferedImage senderWidImage = ImageIO.read(new File(DATA_PATH + senderDidIpfsHash + "/PublicShare.png")); - String senderWidBin = PropImage.img2bin(senderWidImage); - if (senderMutex) { APIResponse.put("did", senderDidIpfsHash); @@ -145,7 +143,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } - add(TOKENS_PATH + tokens.get(i), ipfs); + String hash = add(TOKENS_PATH + tokens.get(i), ipfs); + pin(hash, ipfs); String tokenChainHash = add(TOKENCHAIN_PATH + tokens.get(i) + ".json", ipfs); allTokensChainsPushed.add(tokenChainHash); } @@ -263,6 +262,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String consensusID = calculateHash(senderToken, "SHA3-256"); writeToFile(LOGGER_PATH + "consensusID", consensusID, false); String consensusIDIPFSHash = IPFSNetwork.add(LOGGER_PATH + "consensusID", ipfs); + pin(consensusIDIPFSHash,ipfs); deleteFile(LOGGER_PATH + "consensusID"); JSONObject ipfsObject = new JSONObject(); @@ -301,14 +301,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception peerAuth = input.readLine(); - -// 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")) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); TokenSenderLogger.info("Sender Data Not Available"); @@ -360,9 +352,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } - // output.println(senderDetails2Receiver); - - JSONObject dataObject = new JSONObject(); dataObject.put("tid", tid); dataObject.put("message", consensusIDIPFSHash); @@ -441,7 +430,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception 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(); @@ -604,6 +593,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception // } TokenSenderLogger.info("Transaction Successful"); + System.out.println("Verify Count: " + Authenticate.verifyCount); + Authenticate.verifyCount = 0; executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); output.close(); input.close(); From 259d4e2658af6d6689e4032d6ae0d2233af24985 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 21 Dec 2021 15:28:53 +0530 Subject: [PATCH 06/11] Fix: Block Commit initiator signing Signed-off-by: Nidhin Mahesh A --- .../DataConsensus/BlockCommitProcedure.java | 14 ++-- src/com/rubix/Resources/APIHandler.java | 17 +++++ src/com/rubix/Resources/Functions.java | 37 +++++++--- src/com/rubix/TokenTransfer/BlockSender.java | 69 ++++++++++--------- .../rubix/TokenTransfer/TokenReceiver.java | 54 ++++++++++----- 5 files changed, 128 insertions(+), 63 deletions(-) diff --git a/src/com/rubix/DataConsensus/BlockCommitProcedure.java b/src/com/rubix/DataConsensus/BlockCommitProcedure.java index dbf0ad5c..4a08bd45 100644 --- a/src/com/rubix/DataConsensus/BlockCommitProcedure.java +++ b/src/com/rubix/DataConsensus/BlockCommitProcedure.java @@ -65,15 +65,20 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz int[][] shares = Split.get135Shares(); BlockCommitProcedureLogger.debug("Payload Split Success"); + + JSONObject data1 = new JSONObject(); + JSONObject data2 = new JSONObject(); + + try { + 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 { + BlockCommitProcedureLogger.error("Created Shares Q1 to Q4"); + senderSignQ = getSignFromShares(pvt, authSenderByQuorumHash); data1.put("sign", senderSignQ); data1.put("senderDID", senderDidIpfs); @@ -87,8 +92,9 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz data2.put("Share3", Q3Share); data2.put("Share4", Q4Share); } catch (JSONException | IOException e) { - BlockCommitProcedureLogger.error("JSON Exception occurred", e); + BlockCommitProcedureLogger.error("JSON Exception occurred at getSignFromShares", e); e.printStackTrace(); + } JSONArray detailsForQuorum = new JSONArray(); diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index a115425d..2b76c5f8 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -13,7 +13,9 @@ 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; @@ -122,6 +124,7 @@ public static JSONObject send(String data) throws Exception { } if(dataObject.has("blockHash")) { + APILogger.info("Block Transfer Initiated"); UserResponse = BlockSender.Send(dataObject.toString(), ipfs, SEND_PORT); } @@ -267,6 +270,20 @@ public static String networkInfo() throws IOException, JSONException { return resultArray.toString(); } + 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 get list transactions between two mentioned dates * @param s Start Date diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 7f0021d6..0895b255 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1,14 +1,20 @@ package com.rubix.Resources; -import com.rubix.AuthenticateNode.PropImage; -import io.ipfs.api.*; -import org.apache.log4j.*; -import org.json.*; +import static com.rubix.Resources.IPFSNetwork.checkSwarmConnect; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.forwardCheck; +import static com.rubix.Resources.IPFSNetwork.listen; -import javax.imageio.ImageIO; import java.awt.image.BufferedImage; -import java.io.*; -import java.net.*; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; @@ -16,10 +22,21 @@ import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; + +import javax.imageio.ImageIO; + +import com.rubix.AuthenticateNode.PropImage; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; -import static com.rubix.Resources.APIHandler.*; -import static com.rubix.Resources.IPFSNetwork.*; +import io.ipfs.api.IPFS; public class Functions { diff --git a/src/com/rubix/TokenTransfer/BlockSender.java b/src/com/rubix/TokenTransfer/BlockSender.java index 55339afe..e63255c4 100644 --- a/src/com/rubix/TokenTransfer/BlockSender.java +++ b/src/com/rubix/TokenTransfer/BlockSender.java @@ -24,7 +24,6 @@ import java.io.BufferedReader; import java.io.File; import java.io.IOException; -import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.security.NoSuchAlgorithmException; @@ -36,6 +35,7 @@ import com.rubix.AuthenticateNode.PropImage; import com.rubix.Consensus.InitiatorConsensus; import com.rubix.Consensus.InitiatorProcedure; +import com.rubix.DataConsensus.BlockCommitProcedure; import com.rubix.Resources.IPFSNetwork; import org.apache.log4j.Logger; @@ -76,6 +76,8 @@ public class BlockSender { */ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception { + BlockSenderLogger.debug("Initiating Block Commit Procedure..."); + JSONObject APIResponse = new JSONObject(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); // String receiverPeerId; @@ -187,6 +189,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception case 2: { quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + BlockSenderLogger.debug("read quorumlist.json"); break; } case 3: { @@ -310,17 +313,17 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception // forward(receiverPeerId, port, receiverPeerId); // BlockSenderLogger.debug("Forwarded to " + receiverPeerId + " on " + port); - senderSocket = new Socket("127.0.0.1", port); + // senderSocket = new Socket("127.0.0.1", port); - input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); - output = new PrintStream(senderSocket.getOutputStream()); + // input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); + // output = new PrintStream(senderSocket.getOutputStream()); long startTime = System.currentTimeMillis(); - output.println(senderPeerID); - BlockSenderLogger.debug("Sent PeerID"); + // output.println(senderPeerID); + // BlockSenderLogger.debug("Sent PeerID"); - peerAuth = input.readLine(); + // peerAuth = input.readLine(); // while ((peerAuth = input.readLine()) == null) { //// forward(receiverPeerId, port, receiverPeerId); @@ -330,25 +333,25 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception //// output = new PrintStream(senderSocket.getOutputStream()); //// output.println(senderPeerID); // } - if (!peerAuth.equals("200")) { - // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - BlockSenderLogger.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; + // if (!peerAuth.equals("200")) { + // // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + // BlockSenderLogger.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); - String tokenAuth = input.readLine(); + // String tokenAuth = input.readLine(); // if (!tokenAuth.equals("200")) { // String errorMessage = null; @@ -385,7 +388,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception JSONObject dataObject = new JSONObject(); dataObject.put("tid", tid); - // dataObject.put("message", consensusIDIPFSHash); + dataObject.put("message", blockHash); dataObject.put("blockHash", blockHash); dataObject.put("pvt", pvt); dataObject.put("senderDidIpfs", senderDidIpfsHash); @@ -396,7 +399,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception BlockSenderLogger.debug("dataobject " + dataObject.toString()); - InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 100, alphaSize); + BlockCommitProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 100, alphaSize); BlockSenderLogger.debug("length on sender " + InitiatorConsensus.quorumSignature.length() + "response count " + InitiatorConsensus.quorumResponse); if (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { @@ -406,9 +409,9 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); // output.println(senderDetails2Receiver); // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - output.close(); - input.close(); - senderSocket.close(); + // output.close(); + // input.close(); + // senderSocket.close(); senderMutex = false; updateQuorum(quorumArray, null, false, type); APIResponse.put("did", senderDidIpfsHash); @@ -435,9 +438,9 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception if (!signatureAuth.equals("200")) { // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); BlockSenderLogger.info("Authentication Failed"); - output.close(); - input.close(); - senderSocket.close(); + // output.close(); + // input.close(); + // senderSocket.close(); senderMutex = false; updateQuorum(quorumArray, null, false, type); APIResponse.put("did", senderDidIpfsHash); @@ -629,9 +632,9 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception BlockSenderLogger.info("Transaction Successful"); // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - output.close(); - input.close(); - senderSocket.close(); + // output.close(); + // input.close(); + // senderSocket.close(); senderMutex = false; return APIResponse; diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 975c35dd..47f4b245 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -1,30 +1,52 @@ 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.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.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.*; - -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); From 08084c1ad36fb6e3c4faacb18b853f2746c83b6f Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 29 Dec 2021 10:29:44 +0530 Subject: [PATCH 07/11] Seperate threads for quorum validations Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 112 ++-- .../DataConsensus/BlockCommitQuorum.java | 578 +++++++++--------- .../rubix/DataConsensus/QuorumPinning.java | 237 +++++++ 3 files changed, 605 insertions(+), 322 deletions(-) create mode 100644 src/com/rubix/DataConsensus/QuorumPinning.java diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index b5e2964c..0149d0d4 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,67 +1,89 @@ package com.rubix.Consensus; +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.readFile; +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.dhtEmpty; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.listen; + +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 = ""; + boolean integrityCheck = true; + String temp, peerID, transactionID, verifySenderHash, receiverDID, receiverPID, appName, senderPrivatePos, + senderDidIpfsHash = "", senderPID = ""; ServerSocket serverSocket = null; Socket socket = null; - try { + try { peerID = getPeerID(DATA_PATH + "DID.json"); String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID); appName = peerID.concat(role); 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())); @@ -72,15 +94,14 @@ public void run() { String getData; String qstReq; - //? check for incoming request for QST - qstReq = dataReq.readLine(); if (qstReq.contains("qstcmrequest")) { - QuorumConsensusLogger.debug("Sender reqesting QuorumSignedTransactions.json and CreditMapping.json: " + qstReq); + QuorumConsensusLogger + .debug("Sender reqesting QuorumSignedTransactions.json and CreditMapping.json: " + qstReq); File creditsMapping = new File(WALLET_DATA_PATH + "CreditMapping.json"); - if(!creditsMapping.exists()) { + if (!creditsMapping.exists()) { QuorumConsensusLogger.debug("File doesn't exist"); creditsMapping.createNewFile(); writeToFile(creditsMapping.toString(), "[]", false); @@ -89,9 +110,9 @@ public void run() { JSONObject qstObjectSend; JSONArray creditsArray = new JSONArray(); String credits = ""; - if(qstContent.length() > 0) { + if (qstContent.length() > 0) { qstObjectSend = qstContent.getJSONObject(qstContent.length() - 1); - if(!qstObjectSend.has("minestatus")) { + if (!qstObjectSend.has("minestatus")) { QuorumConsensusLogger.debug("Entering Credits Security"); credits = qstObjectSend.getString("credits"); if (!credits.equals("")) { @@ -114,8 +135,7 @@ public void run() { if (getData.contains("ping check")) { QuorumConsensusLogger.debug("Ping check from sender: " + getData); out.println("pong response"); - } - else { + } else { QuorumConsensusLogger.debug("Received Details from initiator: " + getData); readSenderData = new JSONObject(getData); senderPrivatePos = readSenderData.getString("sign"); @@ -127,7 +147,8 @@ public void run() { senderPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", senderDidIpfsHash); receiverPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", receiverDID); - String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", senderDidIpfsHash); + String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", + senderDidIpfsHash); nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); String quorumHash = calculateHash(verifySenderHash.concat(receiverDID), "SHA3-256"); @@ -137,25 +158,25 @@ public void run() { detailsToVerify.put("hash", verifySenderHash); detailsToVerify.put("signature", senderPrivatePos); - -// 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; + // 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 (Authenticate.verifySignature(detailsToVerify.toString())) { QuorumConsensusLogger.debug("Quorum Authenticated Sender"); - if(!dhtEmpty(verifySenderHash, ipfs)) { + if (!dhtEmpty(verifySenderHash, ipfs)) { QuorumConsensusLogger.debug("ConsensusID pass"); - String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", quorumHash); + 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 + 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); @@ -181,7 +202,8 @@ public void run() { creditMappingArray.put(creditMappingObject); - writeToFile(WALLET_DATA_PATH + "CreditMapping.json", creditMappingArray.toString(), false); + writeToFile(WALLET_DATA_PATH + "CreditMapping.json", creditMappingArray.toString(), + false); } JSONObject storeDetailsQuorum = new JSONObject(); @@ -212,7 +234,7 @@ public void run() { data.put(storeDetailsQuorum); updateJSON("add", WALLET_DATA_PATH + "QuorumSignedTransactions.json", data.toString()); } - }else{ + } else { QuorumConsensusLogger.debug("Sender Authentication Failure - ConsensusID"); out.println("Auth_Failed"); } @@ -226,10 +248,10 @@ public void run() { } catch (JSONException e) { QuorumConsensusLogger.error("JSONException Occurred", e); } catch (NullPointerException e) { - QuorumConsensusLogger.error("NullPointer Exception Occurred ",e); + QuorumConsensusLogger.error("NullPointer Exception Occurred ", e); } - finally{ + finally { try { socket.close(); serverSocket.close(); diff --git a/src/com/rubix/DataConsensus/BlockCommitQuorum.java b/src/com/rubix/DataConsensus/BlockCommitQuorum.java index 74e9615e..a661d74b 100644 --- a/src/com/rubix/DataConsensus/BlockCommitQuorum.java +++ b/src/com/rubix/DataConsensus/BlockCommitQuorum.java @@ -1,277 +1,301 @@ -package com.rubix.DataConsensus; - -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.readFile; -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.listen; - -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.Constants.ConsensusConstants; -import com.rubix.Resources.IPFSNetwork; - -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; - -public class BlockCommitQuorum implements Runnable { - - public static Logger BlockCommitQuorumLogger = Logger.getLogger(BlockCommitQuorum.class); - - /** - * This method is used to run a thread for Quorum Members - *

- * This involves - *

    - *
  1. Verify sender signature
  2. - *
  3. Signing the transaction
  4. - *
  5. Receiving share from sender
  6. - *
- */ - - int port; - IPFS ipfs; - String role; - int round; - - public BlockCommitQuorum(String role, int port) { - this.role = role; - this.port = 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, blockHash, receiverPID, appName, senderPrivatePos, - senderDidIpfsHash = "", senderPID = ""; - ServerSocket serverSocket = null; - Socket socket = null; - try { - - peerID = getPeerID(DATA_PATH + "DID.json"); - String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID); - appName = peerID.concat(role); - - listen(appName, port); - - BlockCommitQuorumLogger.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 - - qstReq = dataReq.readLine(); - if (qstReq.contains("qstcmrequest")) { - - BlockCommitQuorumLogger - .debug("Sender reqesting QuorumSignedTransactions.json and CreditMapping.json: " + qstReq); - - File creditsMapping = new File(WALLET_DATA_PATH + "CreditMapping.json"); - if (!creditsMapping.exists()) { - BlockCommitQuorumLogger.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); - - String cmFileHash = IPFSNetwork.add(WALLET_DATA_PATH + "CreditMapping.json", ipfs); - - JSONObject qResponse = new JSONObject(); - qResponse.put("QuorumSignedTransactions", qstObjectSend.toString()); - qResponse.put("CreditMapping", cmFileHash); - - dataResp.println(qResponse.toString()); - } - - // TODO: if the incoming request contains the keyword "request", push the QST to - // IPFS and send the two hashes back to the sender. - - // ? This is where quorum fetched the data send from initiatorConsensus (Line - // 148) - - getData = in.readLine(); - if (getData.contains("ping check")) { - BlockCommitQuorumLogger.debug("Ping check from sender: " + getData); - out.println("pong response"); - } else { - BlockCommitQuorumLogger.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"); - blockHash = readSenderData.getString(ConsensusConstants.BLOCK); - - senderPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", senderDidIpfsHash); - // receiverPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", blockHash); - - String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", - senderDidIpfsHash); - - nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); - String quorumHash = calculateHash(verifySenderHash.concat(blockHash), "SHA3-256"); - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", senderDidIpfsHash); - detailsToVerify.put("hash", verifySenderHash); - detailsToVerify.put("signature", senderPrivatePos); - - // BlockCommitQuorumLogger.debug("Checking providers for: " + verifySenderHash); - // ArrayList dhtOwnersList = dhtOwnerCheck(verifySenderHash); - // BlockCommitQuorumLogger.debug("Providers: " + dhtOwnersList); - // boolean consensusIDcheck = true; - // 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"); - - //TODO: check minimum balance of sender is one RBT - - //TODO: verifying the block hash, fetching block hash and pinning files in block file. - if (Authenticate.verifySignature(detailsToVerify.toString())) { - BlockCommitQuorumLogger.debug("Quorum Authenticated Sender"); - - IPFSNetwork.pin(blockHash, ipfs); - - pinBlockFiles(blockHash, ipfs); - String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - quorumHash); - out.println(QuorumSignature); - String creditval; - creditval = in.readLine(); - BlockCommitQuorumLogger.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); - - } - - JSONObject storeDetailsQuorum = new JSONObject(); - storeDetailsQuorum.put("tid", transactionID); - storeDetailsQuorum.put("consensusID", verifySenderHash); - storeDetailsQuorum.put("sign", senderPrivatePos); - storeDetailsQuorum.put("credits", credit); - storeDetailsQuorum.put("senderdid", senderDidIpfsHash); - - //? During mining if QST file has blockHash instead of recieverID, then credit is counted as 2 for that transaction. - storeDetailsQuorum.put("blockHash", blockHash); - - JSONArray data = new JSONArray(); - data.put(storeDetailsQuorum); - BlockCommitQuorumLogger.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"); - BlockCommitQuorumLogger.debug("added consensus ID " + consenusIDhash); - } - } else { - BlockCommitQuorumLogger.debug("Sender Authentication Failure - Quorum"); - out.println("Auth_Failed"); - } - } - } catch (IOException e) { - BlockCommitQuorumLogger.error("IOException Occurred", e); - } catch (JSONException e) { - BlockCommitQuorumLogger.error("JSONException Occurred", e); - } catch (NullPointerException e) { - BlockCommitQuorumLogger.error("NullPointer Exception Occurred ", e); - } - - finally { - try { - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } catch (IOException e) { - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - BlockCommitQuorumLogger.error("IOException Occurred", e); - } - - } - } - - } - - private void pinBlockFiles(String blockHash, IPFS ipfs) throws JSONException { - 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); - } - - } -} +// package com.rubix.DataConsensus; + +// 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.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.listen; + +// 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.Constants.ConsensusConstants; +// import com.rubix.Resources.IPFSNetwork; + +// 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; + +// public class BlockCommitQuorum implements Runnable { + +// public static Logger BlockCommitQuorumLogger = +// Logger.getLogger(BlockCommitQuorum.class); + +// /** +// * This method is used to run a thread for Quorum Members +// *

+// * This involves +// *

    +// *
  1. Verify sender signature
  2. +// *
  3. Signing the transaction
  4. +// *
  5. Receiving share from sender
  6. +// *
+// */ + +// int port; +// IPFS ipfs; +// String role; +// int round; + +// public BlockCommitQuorum(String role, int port) { +// this.role = role; +// this.port = 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, blockHash, receiverPID, +// appName, senderPrivatePos, +// senderDidIpfsHash = "", senderPID = ""; +// ServerSocket serverSocket = null; +// Socket socket = null; +// try { + +// peerID = getPeerID(DATA_PATH + "DID.json"); +// String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", +// peerID); +// appName = peerID.concat(role); + +// listen(appName, port); + +// BlockCommitQuorumLogger.debug("Quorum Listening on " + port + " appname " + +// appName); +// serverSocket = new ServerSocket(port); +// socket = serverSocket.accept(); + +// BufferedReader in = new BufferedReader(new +// InputStreamReader(socket.getInputStream())); +// PrintStream out = new PrintStream(socket.getOutputStream()); + +// JSONObject readSenderData; +// String getData; + +// // ? check for incoming request for QST + +// // qstReq = dataReq.readLine(); +// // if (qstReq.contains("qstcmrequest")) { + +// // BlockCommitQuorumLogger +// // .debug("Sender reqesting QuorumSignedTransactions.json and +// // CreditMapping.json: " + qstReq); + +// // File creditsMapping = new File(WALLET_DATA_PATH + "CreditMapping.json"); +// // if (!creditsMapping.exists()) { +// // BlockCommitQuorumLogger.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); + +// // String cmFileHash = IPFSNetwork.add(WALLET_DATA_PATH + +// "CreditMapping.json", +// // ipfs); + +// // JSONObject qResponse = new JSONObject(); +// // qResponse.put("QuorumSignedTransactions", qstObjectSend.toString()); +// // qResponse.put("CreditMapping", cmFileHash); + +// // dataResp.println(qResponse.toString()); +// // } + +// // TODO: if the incoming request contains the keyword "request", push the QST +// to +// // IPFS and send the two hashes back to the sender. + +// // ? This is where quorum fetched the data send from initiatorConsensus (Line +// // 148) + +// getData = in.readLine(); +// if (getData.contains("ping check")) { +// BlockCommitQuorumLogger.debug("Ping check from sender: " + getData); +// out.println("pong response"); +// } else { +// BlockCommitQuorumLogger.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"); +// blockHash = readSenderData.getString(ConsensusConstants.BLOCK); + +// senderPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", +// senderDidIpfsHash); +// // receiverPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", +// // blockHash); + +// String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", +// "walletHash", "didHash", +// senderDidIpfsHash); + +// nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); +// String quorumHash = calculateHash(verifySenderHash.concat(blockHash), +// "SHA3-256"); + +// JSONObject detailsToVerify = new JSONObject(); +// detailsToVerify.put("did", senderDidIpfsHash); +// detailsToVerify.put("hash", verifySenderHash); +// detailsToVerify.put("signature", senderPrivatePos); + +// // BlockCommitQuorumLogger.debug("Checking providers for: " + +// verifySenderHash); +// // ArrayList dhtOwnersList = dhtOwnerCheck(verifySenderHash); +// // BlockCommitQuorumLogger.debug("Providers: " + dhtOwnersList); +// // boolean consensusIDcheck = true; +// // 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"); + +// // TODO: check minimum balance of sender is one RBT + +// // TODO: verifying the block hash, fetching block hash and pinning files in +// // block file. +// if (Authenticate.verifySignature(detailsToVerify.toString())) { +// BlockCommitQuorumLogger.debug("Quorum Authenticated Sender"); + +// IPFSNetwork.pin(blockHash, ipfs); + +// pinBlockFiles(blockHash, ipfs); +// String QuorumSignature = getSignFromShares(DATA_PATH + didHash + +// "/PrivateShare.png", +// quorumHash); +// out.println(QuorumSignature); +// String creditval; +// creditval = in.readLine(); +// BlockCommitQuorumLogger.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); + +// } + +// JSONObject storeDetailsQuorum = new JSONObject(); +// storeDetailsQuorum.put("tid", transactionID); +// storeDetailsQuorum.put("consensusID", verifySenderHash); +// storeDetailsQuorum.put("sign", senderPrivatePos); +// storeDetailsQuorum.put("credits", credit); +// storeDetailsQuorum.put("senderdid", senderDidIpfsHash); + +// // ? During mining if QST file has blockHash instead of recieverID, then +// credit +// // is counted as 2 for that transaction. +// storeDetailsQuorum.put("blockHash", blockHash); + +// JSONArray data = new JSONArray(); +// data.put(storeDetailsQuorum); +// BlockCommitQuorumLogger.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"); +// BlockCommitQuorumLogger.debug("added consensus ID " + consenusIDhash); +// } +// } else { +// BlockCommitQuorumLogger.debug("Sender Authentication Failure - Quorum"); +// out.println("Auth_Failed"); +// } +// } +// } catch (IOException e) { +// BlockCommitQuorumLogger.error("IOException Occurred", e); +// } catch (JSONException e) { +// BlockCommitQuorumLogger.error("JSONException Occurred", e); +// } catch (NullPointerException e) { +// BlockCommitQuorumLogger.error("NullPointer Exception Occurred ", e); +// } + +// finally { +// try { +// socket.close(); +// serverSocket.close(); +// executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); +// } catch (IOException e) { +// executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); +// BlockCommitQuorumLogger.error("IOException Occurred", e); +// } + +// } +// } + +// } + +// private void pinBlockFiles(String blockHash, IPFS ipfs) throws JSONException +// { +// 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); +// } + +// } +// } diff --git a/src/com/rubix/DataConsensus/QuorumPinning.java b/src/com/rubix/DataConsensus/QuorumPinning.java new file mode 100644 index 00000000..4ccde6fd --- /dev/null +++ b/src/com/rubix/DataConsensus/QuorumPinning.java @@ -0,0 +1,237 @@ +package com.rubix.DataConsensus; + +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.updateJSON; +import static com.rubix.Resources.Functions.writeToFile; +import static com.rubix.Resources.IPFSNetwork.add; +import static com.rubix.Resources.IPFSNetwork.listen; + +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.Constants.ConsensusConstants; +import com.rubix.Resources.IPFSNetwork; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONObject; + +import io.ipfs.api.IPFS; + +public class QuorumPinning implements Runnable { + + public static Logger QuorumPinningLogger = Logger.getLogger(QuorumPinning.class); + + int port; + IPFS ipfs; + String role; + int round; + + public QuorumPinning(String role, int port) { + this.role = role; + this.port = 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"); + String peerID, appName; + ServerSocket serverSocket = null; + Socket socket = null; + + try { + + peerID = getPeerID(DATA_PATH + "DID.json"); + String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID); + appName = peerID.concat(role); + + listen(appName, port); + + QuorumPinningLogger.debug("Quorum Listening on " + port + " appname " + appName); + serverSocket = new ServerSocket(port); + socket = serverSocket.accept(); + + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + PrintStream out = new PrintStream(socket.getOutputStream()); + + Thread validate = new SenderHandler(socket, in, out, ipfs, peerID, didHash, appName); + validate.start(); + + } catch (IOException e) { + QuorumPinningLogger.error("Error in QuorumPinning: " + e.getMessage()); + } + + } + } +} + +class SenderHandler extends Thread { + + public static Logger SenderHandlerLogger = Logger.getLogger(SenderHandler.class); + + final Socket socket; + final BufferedReader in; + final PrintStream out; + final IPFS ipfs; + final String peerID; + final String didHash; + final String appName; + + public SenderHandler(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(); + } + + boolean integrityCheck = true; + String temp = ""; + String transactionID = ""; + String verifySenderHash = ""; + String blockHash = ""; + String senderPrivatePos = ""; + String senderDidIpfsHash = ""; + String senderPID = ""; + String getData; + + JSONObject readSenderData; + + public void run() { + + while (true) { + try { + getData = in.readLine(); + + if (getData.contains("ping check")) { + SenderHandlerLogger.debug("Ping check from sender: " + getData); + out.println("pong response"); + } else { + SenderHandlerLogger.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"); + blockHash = readSenderData.getString(ConsensusConstants.BLOCK); + + 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(blockHash), "SHA3-256"); + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", senderDidIpfsHash); + detailsToVerify.put("hash", verifySenderHash); + detailsToVerify.put("signature", senderPrivatePos); + + if (Authenticate.verifySignature(detailsToVerify.toString())) { + SenderHandlerLogger.debug("Quorum Authenticated 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); + } + + String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + quorumHash); + out.println(QuorumSignature); + String creditval; + creditval = in.readLine(); + SenderHandlerLogger.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); + + } + + 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); + SenderHandlerLogger.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"); + SenderHandlerLogger.debug("added consensus ID " + consenusIDhash); + } + } else { + SenderHandlerLogger.debug("Sender Authentication Failure - Quorum"); + out.println("Auth_Failed"); + } + } + } catch (Exception e) { + SenderHandlerLogger.error("Exception in SenderHandler: " + e); + } + } + } + +} \ No newline at end of file From e916752a5c86b3778b1e9cce80e3082f0ff29ca0 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 29 Dec 2021 12:31:35 +0530 Subject: [PATCH 08/11] transaction type check in Token transfer module Signed-off-by: Nidhin Mahesh A --- .../rubix/AuthenticateNode/Authenticate.java | 40 +- src/com/rubix/AuthenticateNode/Interact.java | 56 +- src/com/rubix/AuthenticateNode/PropImage.java | 35 +- .../rubix/AuthenticateNode/SecretShare.java | 590 ++++++----- .../rubix/AuthenticateNode/SplitShares.java | 15 +- .../rubix/Constants/ConsensusConstants.java | 11 +- src/com/rubix/Constants/IPFSConstants.java | 8 +- src/com/rubix/Resources/APIHandler.java | 283 ++--- src/com/rubix/Resources/Functions.java | 336 +++--- src/com/rubix/Resources/IPFSNetwork.java | 260 ++--- src/com/rubix/Resources/IntegrityCheck.java | 22 +- src/com/rubix/SplitandStore/Recombine.java | 56 +- src/com/rubix/SplitandStore/Split.java | 249 ++--- src/com/rubix/TokenTransfer/BlockSender.java | 642 ----------- src/com/rubix/TokenTransfer/ProofCredits.java | 155 +-- .../rubix/TokenTransfer/TokenReceiver.java | 117 +- src/com/rubix/TokenTransfer/TokenSender.java | 995 ++++++++++-------- 17 files changed, 1775 insertions(+), 2095 deletions(-) delete mode 100644 src/com/rubix/TokenTransfer/BlockSender.java diff --git a/src/com/rubix/AuthenticateNode/Authenticate.java b/src/com/rubix/AuthenticateNode/Authenticate.java index f5674dc3..866cc40b 100644 --- a/src/com/rubix/AuthenticateNode/Authenticate.java +++ b/src/com/rubix/AuthenticateNode/Authenticate.java @@ -1,30 +1,42 @@ 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 */ @@ -36,7 +48,7 @@ public static boolean verifySignature(String detailString) throws IOException, J 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); @@ -49,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)); @@ -60,7 +72,8 @@ 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())) { return true; } else { @@ -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= 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 */ @@ -395,14 +432,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); } @@ -412,12 +449,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 @@ -430,10 +468,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); @@ -444,6 +485,7 @@ public static JSONArray transactionsByComment(String comment) throws JSONExcepti /** * 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 @@ -454,8 +496,9 @@ 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; @@ -464,8 +507,8 @@ public static JSONArray transactionsByDID(String did) throws JSONException { 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; @@ -474,11 +517,10 @@ public static int onlinePeersCount() throws JSONException, IOException, Interrup 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"; } @@ -489,7 +531,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")) @@ -498,21 +540,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(); @@ -520,16 +563,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"); @@ -543,6 +585,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 */ @@ -550,7 +593,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; @@ -558,6 +601,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 */ @@ -565,18 +609,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++; } } @@ -592,7 +636,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 0895b255..5ee0029f 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -38,7 +38,6 @@ import io.ipfs.api.IPFS; - public class Functions { public static boolean mutex = false; @@ -48,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; @@ -118,22 +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 + "/"); @@ -173,7 +171,6 @@ public static void nodeData(String did, String wid, IPFS ipfs) throws IOExceptio } } - /** * This method gets the currently logged in username * @@ -208,9 +205,9 @@ 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 @@ -277,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 * @@ -305,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) { @@ -353,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 * @@ -398,7 +395,6 @@ public static void listenThread(JSONObject connectObject) { } - /** * This function converts any integer to its binary form * @@ -485,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 @@ -522,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 */ @@ -531,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 */ @@ -539,7 +538,6 @@ public static int minQuorum(int count) { return (((count - 1) / 3) * 2) + 1; } - /** * This method checks if Quorum is available for consensus * @@ -550,7 +548,7 @@ 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 { @@ -565,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; } @@ -575,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 * @@ -606,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; @@ -624,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++) { @@ -636,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]; @@ -693,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 @@ -722,41 +716,43 @@ 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(); @@ -802,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(); @@ -864,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 */ @@ -873,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", @@ -895,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; } @@ -914,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(); @@ -944,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); @@ -971,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(); @@ -1001,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); @@ -1036,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(); @@ -1049,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); @@ -1074,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; } @@ -1086,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 b948580c..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 @@ -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(bootstrap) || command.contains("findprovs")) { + || command.contains(p2p) || command.contains(shutdown) || command.contains(bootstrap) + || command.contains("findprovs")) { p = new ProcessBuilder(commands); process = p.start(); @@ -562,12 +578,20 @@ public static void swarmConnectP2P(String peerid, IPFS ipfs) throws JSONExceptio 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 allTokensChainsPushed = new ArrayList(); - APIResponse = new JSONObject(); - - // if (tokens.length() == 0) { - - // APIResponse.put("did", senderDidIpfsHash); - // APIResponse.put("tid", "null"); - // APIResponse.put("status", "Failed"); - // APIResponse.put("message", "No balance"); - // senderMutex = false; - // return APIResponse; - // } - - // 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"); - // BlockSenderLogger.debug(token + "and " + tokenchain); - // if (!(token.exists() && tokenchain.exists())) { - // BlockSenderLogger.info("Tokens Not Verified"); - // senderMutex = false; - // APIResponse.put("did", senderDidIpfsHash); - // APIResponse.put("tid", "null"); - // APIResponse.put("status", "Failed"); - // APIResponse.put("message", "Invalid token(s)"); - // return APIResponse; - - // } - // add(TOKENS_PATH + tokens.get(i), ipfs); - // String tokenChainHash = add(TOKENCHAIN_PATH + tokens.get(i) + ".json", ipfs); - // allTokensChainsPushed.add(tokenChainHash); - // } - - String authSenderByRecHash = calculateHash( - blockHash + comment, "SHA3-256"); - String tid = calculateHash(authSenderByRecHash + comment, "SHA3-256"); - BlockSenderLogger.debug("Sender by Receiver Hash " + authSenderByRecHash); - BlockSenderLogger.debug("TID on sender " + tid); - - 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(senderDidIpfsHash), false); - String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); - deleteFile(LOGGER_PATH + "tempgamma"); - - switch (type) { - case 1: { - quorumArray = getQuorum(betaHash, gammaHash, senderDidIpfsHash, senderDidIpfsHash, 1); - break; - } - - case 2: { - quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); - BlockSenderLogger.debug("read quorumlist.json"); - break; - } - case 3: { - quorumArray = detailsObject.getJSONArray("quorum"); - break; - } - default: { - BlockSenderLogger.error("Unknown quorum type input, cancelling transaction"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Unknown quorum type input, cancelling transaction"); - return APIResponse; - - } - } - - QuorumSwarmConnect(quorumArray, ipfs); - - 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)); - } - - BlockSenderLogger.debug("alphaquorum " + alphaQuorum + " size " + alphaQuorum.length()); - BlockSenderLogger.debug("betaquorum " + betaQuorum + " size " + betaQuorum.length()); - BlockSenderLogger.debug("gammaquorum " + gammaQuorum + " size " + gammaQuorum.length()); - - alphaPeersList = QuorumCheck(alphaQuorum, alphaSize); - betaPeersList = QuorumCheck(betaQuorum, 7); - gammaPeersList = QuorumCheck(gammaQuorum, 7); - - // for(int i=0;i= minQuorum(7))) { - BlockSenderLogger.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; - - } - - BlockSenderLogger.debug("Consensus Reached"); - senderDetails2Receiver.put("status", "Consensus Reached"); - senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); - - // output.println(senderDetails2Receiver); - // output.println("Consensus Reached"); - BlockSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); - // output.println(InitiatorConsensus.quorumSignature); - - String signatureAuth = input.readLine(); - - long endAuth = System.currentTimeMillis(); - long totalTime = endAuth - startTime; - if (!signatureAuth.equals("200")) { - // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - BlockSenderLogger.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); - - // BlockSenderLogger.debug("Unpinned Tokens"); - // output.println("Unpinned"); - - // String confirmation = input.readLine(); - // if (!confirmation.equals("Successfully Pinned")) { - // BlockSenderLogger.warn("Multiple Owners for the token"); - // // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - // BlockSenderLogger.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", "Receiver process not over"); - // BlockSenderLogger.info("Incomplete Transaction"); - // return APIResponse; - - // } - - //? below code is verified for block sender logic - - 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", "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()); - - // 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("blockHash", blockHash); - // 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(); - // BlockSenderLogger.debug("Sending 'POST' request to URL : " + url); - // BlockSenderLogger.debug("Post Data : " + postJsonData); - // BlockSenderLogger.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(); - - // BlockSenderLogger.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(); - // BlockSenderLogger.debug("Sending 'POST' request to URL : " + - // urlQuorumUpdate); - // BlockSenderLogger.debug("Post Data : " + populateQuorumUpdate); - // BlockSenderLogger.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(); - // - // } - - BlockSenderLogger.info("Transaction Successful"); - // executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - // output.close(); - // input.close(); - // senderSocket.close(); - senderMutex = false; - return APIResponse; - - } -} diff --git a/src/com/rubix/TokenTransfer/ProofCredits.java b/src/com/rubix/TokenTransfer/ProofCredits.java index 5eab47b1..22387108 100644 --- a/src/com/rubix/TokenTransfer/ProofCredits.java +++ b/src/com/rubix/TokenTransfer/ProofCredits.java @@ -1,18 +1,32 @@ package com.rubix.TokenTransfer; +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.PAYMENTS_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.SYNC_IP; +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.getQuorum; +import static com.rubix.Resources.Functions.minQuorum; +import static com.rubix.Resources.Functions.mineUpdate; +import static com.rubix.Resources.Functions.readFile; +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.repo; -import com.rubix.Consensus.InitiatorConsensus; -import com.rubix.Consensus.InitiatorProcedure; -import com.rubix.Resources.Functions; -import com.rubix.Resources.IPFSNetwork; -import io.ipfs.api.IPFS; -import org.apache.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import javax.net.ssl.HttpsURLConnection; -import java.io.*; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.DateFormat; @@ -23,12 +37,21 @@ import java.util.Iterator; import java.util.List; -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.repo; +import javax.net.ssl.HttpsURLConnection; +import com.rubix.Consensus.InitiatorConsensus; +import com.rubix.Consensus.InitiatorProcedure; +import com.rubix.Resources.Functions; +import com.rubix.Resources.IPFSNetwork; -public class ProofCredits { +import org.apache.log4j.Logger; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import io.ipfs.api.IPFS; +public class ProofCredits { public static Logger ProofCreditsLogger = Logger.getLogger(ProofCredits.class); private static ArrayList quorumPeersList; @@ -52,21 +75,41 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONArray betaQuorum = new JSONArray(); JSONArray gammaQuorum = new JSONArray(); - int creditsRequired = 50000, level; long starttime = System.currentTimeMillis(); JSONArray resJsonData = new JSONArray(); new JSONObject(); JSONObject resJsonData_credit; + // Clean up old File + String qstFile = readFile(WALLET_DATA_PATH + "QuorumSignedTransactions.json"); + JSONArray qstArray = new JSONArray(qstFile); + File usedCreditsFile = new File(WALLET_DATA_PATH + "MinedCreditsHistory.json"); + if (!usedCreditsFile.exists()) { + writeToFile(String.valueOf(usedCreditsFile), "[]", false); + } - //Reading proofcredits.json - String jsonFilePath = WALLET_DATA_PATH + "QuorumSignedTransactions.json"; - JSONArray records = new JSONArray(readFile(jsonFilePath)); - int balance = records.length(); - JSONArray prooftid = new JSONArray(); - int availableCredits = records.length(); + JSONArray newQstArrayReplace = new JSONArray(); + JSONArray minedArray = new JSONArray(readFile(WALLET_DATA_PATH + "MinedCreditsHistory.json")); + if (qstArray.getJSONObject(0).has("minestatus")) { + for (int i = 0; i < qstArray.length(); i++) { + if (qstArray.getJSONObject(i).has("minestatus")) { + if (qstArray.getJSONObject(i).getBoolean("minestatus")) + minedArray.put(qstArray.getJSONObject(i)); + else { + qstArray.getJSONObject(i).remove("minestatus"); + newQstArrayReplace.put(qstArray.getJSONObject(i)); + } + } + } + writeToFile(WALLET_DATA_PATH + "QuorumSignedTransactions.json", newQstArrayReplace.toString(), false); + writeToFile(WALLET_DATA_PATH + "MinedCreditsHistory.json", minedArray.toString(), false); + } + + JSONArray newQstArray = new JSONArray(readFile(WALLET_DATA_PATH + "QuorumSignedTransactions.json")); + int availableCredits = newQstArray.length(); + ProofCreditsLogger.debug("Credits available: " + availableCredits); String GET_URL_credit = SYNC_IP + "/getlevel"; URL URLobj_credit = new URL(GET_URL_credit); HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); @@ -82,12 +125,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } in_credit.close(); ProofCreditsLogger.debug("response from service " + response_credit.toString()); - - //JSONObject responseJSON=new JSONObject(response.toString()); - //resJsonData= responseJSON.getJSONArray("data"); - //creditUsed = responseJSON.getInt("credits"); - - resJsonData_credit = new JSONObject(response_credit.toString()); int level_credit = resJsonData_credit.getInt("level"); creditsRequired = (int) Math.pow(2, (2 + level_credit)); @@ -96,13 +133,11 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } else ProofCreditsLogger.debug("GET request not worked"); - ProofCreditsLogger.debug("credits required " + creditsRequired + " available credits " + availableCredits); if (availableCredits >= 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 47f4b245..58aa0b5d 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -8,11 +8,13 @@ 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; @@ -57,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() { @@ -89,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); @@ -99,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(); @@ -108,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()) { @@ -118,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(); @@ -126,26 +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: "); - 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("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"); + 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<>(); @@ -156,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(IPFSNetwork.dhtEmpty(getCIDipfsHash, ipfs)){ - String errorMessage = "Consensus ID issue"; + 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(); @@ -202,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"); @@ -223,16 +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")) { + TokenReceiverLogger.debug("Quorum Signatures: " + QuorumDetails); quorumSignatures = new JSONObject(QuorumDetails); - - String verifyQuorumHash = calculateHash(getCIDipfsHash.concat(receiverDidIpfsHash), "SHA3-256"); + int alphaSize = quorumSignatures.length() - 10; + 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()) { @@ -241,14 +230,11 @@ else if(!(ipfsGetFlag == tokenCount)){ } for (String quorumDidIpfsHash : quorumDID) { - String quorumWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", quorumDidIpfsHash); + syncDataTable(quorumDidIpfsHash, null); + 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"); - } + nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); } for (int i = 0; i < quorumSignatures.length(); i++) { @@ -268,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); @@ -276,6 +264,7 @@ else if(!(ipfsGetFlag == tokenCount)){ detailsForVerify.put("signature", senderSignature); boolean yesSender = Authenticate.verifySignature(detailsForVerify.toString()); + TokenReceiverLogger.debug("Quorum Auth : " + yesQuorum + "Sender Auth : " + yesSender); if (!(yesSender && yesQuorum)) { output.println("420"); APIResponse.put("did", senderDidIpfsHash); @@ -283,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(); @@ -353,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"); @@ -361,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(); @@ -412,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 71694e1d..d9170598 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -1,55 +1,84 @@ package com.rubix.TokenTransfer; -import com.rubix.AuthenticateNode.Authenticate; -import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Consensus.InitiatorConsensus; +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 @@ -64,18 +93,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(); @@ -94,16 +115,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); if (senderMutex) { APIResponse.put("did", senderDidIpfsHash); @@ -116,6 +131,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(); @@ -132,7 +153,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; @@ -143,462 +164,514 @@ 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); + // 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); - - 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; - - } - } - - QuorumSwarmConnect(quorumArray, ipfs); - - 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)); - } - - TokenSenderLogger.debug("alphaquorum " + alphaQuorum + " size " + alphaQuorum.length()); - TokenSenderLogger.debug("betaquorum " + betaQuorum + " size " + betaQuorum.length()); - TokenSenderLogger.debug("gammaquorum " + gammaQuorum + " size " + gammaQuorum.length()); - - - alphaPeersList = QuorumCheck(alphaQuorum, alphaSize); - betaPeersList = QuorumCheck(betaQuorum, 7); - gammaPeersList = QuorumCheck(gammaQuorum, 7); - -// 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; - } + } - 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); - - 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"); + TokenSenderLogger.debug("Consensus Reached"); + senderDetails2Receiver.put("status", "Consensus Reached"); 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; - - } - - 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(); - - 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); - APIResponse.put("tid", tid); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender not authenticated"); - return APIResponse; + 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); + 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; - unpin(consensusIDIPFSHash, ipfs); + } + output.println(InitiatorProcedure.essential); + String respAuth = input.readLine(); - repo(ipfs); + if (!respAuth.equals("Send Response")) { - TokenSenderLogger.debug("Unpinned Tokens"); - output.println("Unpinned"); + 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; - String confirmation = input.readLine(); - if (!confirmation.equals("Successfully Pinned")) { - TokenSenderLogger.warn("Multiple Owners for the token"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + } - output.close(); - input.close(); - senderSocket.close(); - senderMutex = false; - updateQuorum(quorumArray, null, false, type); - APIResponse.put("did", senderDidIpfsHash); + 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", "Tokens with multiple pins"); - return APIResponse; - - } - output.println(InitiatorProcedure.essential); - String respAuth = input.readLine(); + 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()); - if (!respAuth.equals("Send Response")) { + 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 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"); - 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; return APIResponse; From 87c0ad030f3707bf17aa8e984282005b81da7958 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 29 Dec 2021 18:24:30 +0530 Subject: [PATCH 09/11] Fix: socket exception error in consensus Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 164 ++---- .../rubix/Consensus/InitiatorProcedure.java | 205 ++++--- src/com/rubix/Consensus/QuorumConsensus.java | 278 +++++++--- .../DataConsensus/BlockCommitInitiator.java | 263 --------- .../DataConsensus/BlockCommitProcedure.java | 146 ----- .../DataConsensus/BlockCommitQuorum.java | 301 ----------- .../rubix/DataConsensus/QuorumPinning.java | 237 -------- src/com/rubix/TokenTransfer/TokenSender.java | 505 ++++++++++++++++++ 8 files changed, 889 insertions(+), 1210 deletions(-) delete mode 100644 src/com/rubix/DataConsensus/BlockCommitInitiator.java delete mode 100644 src/com/rubix/DataConsensus/BlockCommitProcedure.java delete mode 100644 src/com/rubix/DataConsensus/BlockCommitQuorum.java delete mode 100644 src/com/rubix/DataConsensus/QuorumPinning.java diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index b92d55c2..f03da774 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -6,7 +6,7 @@ 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.IPFSNetwork.dhtOwnerCheck; +import static com.rubix.Resources.Functions.syncDataTable; import static com.rubix.Resources.IPFSNetwork.forward; import static com.rubix.Resources.IPFSNetwork.repo; import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; @@ -29,17 +29,15 @@ import io.ipfs.api.IPFS; - public class InitiatorConsensus { public static Logger InitiatorConsensusLogger = Logger.getLogger(InitiatorConsensus.class); - public static volatile JSONObject quorumSignature = new JSONObject(); private static final Object countLock = new Object(); private static final Object signLock = new Object(); public static ArrayList 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(); /** @@ -51,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; @@ -61,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); @@ -89,31 +90,6 @@ private static synchronized void quorumSign(String quorumDID, String hash, Strin } } - public static JSONObject countQuorumSigns(String blockObject) - throws JSONException, InterruptedException, IOException { - - // convert blockHash to a JSONObject - JSONObject response = new JSONObject(); - response.put("blockHash", blockObject); - - // convert blockObject string to json object - JSONObject blockObjectJson = new JSONObject(blockObject); - JSONArray metadataArray = blockObjectJson.getJSONArray("metadata"); - - response.put("files", metadataArray.length()); - - for (int i = 0; i < metadataArray.length(); i++) { - JSONObject metadataObject = metadataArray.getJSONObject(i); - String metadata_hash = metadataObject.getString("metadata_hash"); - ArrayList dhtOwnersList = dhtOwnerCheck(metadata_hash); - response.put(metadata_hash, dhtOwnersList.size()); - } - - response.put("status", "Success"); - - return response; - } - /** * This method runs the consensus * 1. Contact quorum with sender signatures and details @@ -123,9 +99,10 @@ public static JSONObject countQuorumSigns(String blockObject) * @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]; @@ -135,7 +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()); + InitiatorConsensusLogger.debug("quorum peer role " + role + " length " + quorumPeersObject.length()); JSONArray tokenDetails; try { tokenDetails = new JSONArray(details.toString()); @@ -143,7 +120,7 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri JSONObject sharesToken = tokenDetails.getJSONObject(1); String[] shares = new String[minQuorum(7) - 1]; - for(int i = 0; i < shares.length; i++){ + for (int i = 0; i < shares.length; i++) { int p = i + 1; shares[i] = sharesToken.getString("Share" + p); } @@ -157,107 +134,68 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri quorumThreads[i] = new Thread(() -> { 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]); + swarmConnectP2P(quorumID[j], ipfs); + 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); - qSocket[j] = new Socket("127.0.0.1", PORT+j); + 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); + 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 data1 = quorumDetails.getString("CreditMapping"); - JSONArray cmContent = new JSONArray(data1); - - - String data2 = quorumDetails.getString("Credits"); - JSONArray creditsArray = new JSONArray(data2); - if(creditsArray.length() > 0) { - InitiatorConsensusLogger.debug("Entering Credits Security"); - }else - InitiatorConsensusLogger.debug("Old Credits file"); - - -// 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(creditsArray.length() != 0) { - for (int k = 0; k < creditsArray.length(); k++) { - JSONObject object = creditsArray.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] + " " + qResponse[j]); + } else { + 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); + 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); + 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))) {} - InitiatorConsensusLogger.debug("sending Qsign of length " + quorumSignature.length() + "at index " + index); + while (quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { + } + 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 { + } 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]); } } @@ -271,7 +209,9 @@ 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); diff --git a/src/com/rubix/Consensus/InitiatorProcedure.java b/src/com/rubix/Consensus/InitiatorProcedure.java index 3e0372f6..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,109 +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"); - 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(); + 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 0149d0d4..59770aac 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,5 +1,8 @@ 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; @@ -10,13 +13,12 @@ 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.readFile; +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.dhtEmpty; -import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; +import static com.rubix.Resources.IPFSNetwork.pin; import java.io.BufferedReader; import java.io.File; @@ -33,7 +35,6 @@ 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; @@ -68,13 +69,11 @@ public QuorumConsensus(String role, int port) { 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 { + peerID = getPeerID(DATA_PATH + "DID.json"); String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID); appName = peerID.concat(role); @@ -85,79 +84,98 @@ public void run() { 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; + 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; - JSONArray creditsArray = new JSONArray(); - String credits = ""; - if (qstContent.length() > 0) { - qstObjectSend = qstContent.getJSONObject(qstContent.length() - 1); - if (!qstObjectSend.has("minestatus")) { - QuorumConsensusLogger.debug("Entering Credits Security"); - credits = qstObjectSend.getString("credits"); - if (!credits.equals("")) { - String creditContent = IPFSNetwork.get(credits, ipfs); - creditsArray = new JSONArray(creditContent); - } - } - } +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 cmFile = readFile(WALLET_DATA_PATH + "CreditMapping.json"); - JSONArray creditsMappingArray = new JSONArray(cmFile); - JSONObject qResponse = new JSONObject(); - qResponse.put("Credits", creditsArray.toString()); - qResponse.put("CreditMapping", creditsMappingArray.toString()); + boolean integrityCheck = true; + String temp = ""; + String transactionID = ""; + String verifySenderHash = ""; + String blockHash = ""; + String senderPrivatePos = ""; + String senderDidIpfsHash = ""; + String senderPID = ""; + String getData = ""; + String receiverDID = ""; - dataResp.println(qResponse.toString()); - } + JSONObject readSenderData; + + public void run() { + + while (true) { + + try { + + 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); + 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); + 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); @@ -165,31 +183,53 @@ public void run() { // if(dhtOwnersList.size() <= 2 && dhtOwnersList.contains(senderPID)) // consensusIDcheck = true; - if (Authenticate.verifySignature(detailsToVerify.toString())) { - QuorumConsensusLogger.debug("Quorum Authenticated Sender"); - if (!dhtEmpty(verifySenderHash, ipfs)) { - QuorumConsensusLogger.debug("ConsensusID pass"); + // 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(); - QuorumConsensusLogger.debug("credit value " + creditval); + ValidationHandler.debug("credit value " + creditval); - if (!creditval.equals("null")) { // commented as per test for multiple consensus threads + 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(); + // 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"); @@ -202,10 +242,93 @@ public void run() { creditMappingArray.put(creditMappingObject); - writeToFile(WALLET_DATA_PATH + "CreditMapping.json", creditMappingArray.toString(), - false); + } + 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()); + } + + } 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); @@ -215,13 +338,14 @@ public void run() { storeDetailsQuorum.put("recdid", receiverDID); JSONArray data = new JSONArray(); data.put(storeDetailsQuorum); - QuorumConsensusLogger.debug("Quorum Share: " + credit); + 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"); - QuorumConsensusLogger.debug("added consensus ID " + consenusIDhash); + ValidationHandler.debug("added consensus ID " + consenusIDhash); + } else { JSONObject storeDetailsQuorum = new JSONObject(); storeDetailsQuorum.put("tid", transactionID); @@ -234,35 +358,17 @@ public void run() { data.put(storeDetailsQuorum); updateJSON("add", WALLET_DATA_PATH + "QuorumSignedTransactions.json", data.toString()); } + } else { - QuorumConsensusLogger.debug("Sender Authentication Failure - ConsensusID"); + 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 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/DataConsensus/BlockCommitInitiator.java b/src/com/rubix/DataConsensus/BlockCommitInitiator.java deleted file mode 100644 index d27746ff..00000000 --- a/src/com/rubix/DataConsensus/BlockCommitInitiator.java +++ /dev/null @@ -1,263 +0,0 @@ -package com.rubix.DataConsensus; - -import static com.rubix.Resources.Functions.DATA_PATH; -import static com.rubix.Resources.Functions.LOGGER_PATH; -import static com.rubix.Resources.Functions.QUORUM_COUNT; -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.IPFSNetwork.forward; -import static com.rubix.Resources.IPFSNetwork.repo; -import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.net.Socket; -import java.util.ArrayList; - -import com.rubix.AuthenticateNode.Authenticate; -import com.rubix.Resources.IPFSNetwork; - -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; - -public class BlockCommitInitiator { - - public static Logger BlockCommitInitiatorLogger = Logger.getLogger(BlockCommitInitiator.class); - - public static volatile JSONObject quorumSignature = new JSONObject(); - private static final Object countLock = new Object(); - private static final Object signLock = new Object(); - public static ArrayList quorumWithShares = new ArrayList<>(); - public static volatile int[] quorumResponse = { 0, 0, 0 }; - public static volatile JSONArray finalQuorumSignsArray = new JSONArray(); - - /** - * This method increments the quorumResponse variable - */ - private static synchronized boolean voteNCount(int i, int quorumSize) { - boolean status; - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - synchronized (countLock) { - if (quorumResponse[i] < minQuorum(quorumSize)) { - quorumResponse[i]++; - BlockCommitInitiatorLogger.debug("quorum response added index " + i + " is " + quorumResponse[i] - + " quorumsize " + minQuorum(quorumSize)); - status = true; - } else { - status = false; - BlockCommitInitiatorLogger.debug("Consensus Reached for index " + i); - } - } - return status; - } - - /** - * 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) { - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - synchronized (signLock) { - try { - if (quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7)) - && quorumResponse[index] <= minQuorum(quorumSize)) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("did", quorumDID); - jsonObject.put("sign", quorumSignResponse); - jsonObject.put("hash", hash); - finalQuorumSignsArray.put(jsonObject); - quorumSignature.put(quorumDID, quorumSignResponse); - } else { - BlockCommitInitiatorLogger.debug("quorum already reached consensus " + quorumSignature.length()); - } - } catch (JSONException e) { - BlockCommitInitiatorLogger.error("JSON Exception Occurred", e); - e.printStackTrace(); - } - } - } - - /** - * This method runs the consensus - * 1. Contact quorum with sender signatures and details - * 2. Verify quorum signatures - * 3. If consensus reached , sends shares to Quorum - * - * @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 { - String[] qResponse = 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]; - String[] quorumID = new String[QUORUM_COUNT]; - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - JSONObject dataObject = new JSONObject(data); - String hash = dataObject.getString("hash"); - JSONArray details = dataObject.getJSONArray("details"); - quorumResponse[index] = 0; - JSONArray tokenDetails; - try { - tokenDetails = new JSONArray(details.toString()); - JSONObject detailsToken = tokenDetails.getJSONObject(0); - JSONObject sharesToken = tokenDetails.getJSONObject(1); - - String[] shares = new String[minQuorum(7) - 1]; - for (int i = 0; i < shares.length; i++) { - int p = i + 1; - shares[i] = sharesToken.getString("Share" + p); - } - - for (int j = 0; j < quorumPeersObject.length(); j++) - quorumID[j] = quorumPeersObject.getString(j); - - Thread[] quorumThreads = new Thread[quorumPeersObject.length()]; - for (int i = 0; i < quorumPeersObject.length(); i++) { - int j = i; - quorumThreads[i] = new Thread(() -> { - - 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]); - nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); - String appName = quorumID[j].concat(role); - forward(appName, PORT + j, quorumID[j]); - BlockCommitInitiatorLogger.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") { - // BlockCommitInitiatorLogger.warn("Alpha quorum (" + quorumID[j] + ") has no - // credits"); - // } - // if (cmContent.length() == 0 && role == "alpha") { - // BlockCommitInitiatorLogger.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()))) - BlockCommitInitiatorLogger.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)) { - BlockCommitInitiatorLogger.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 { - BlockCommitInitiatorLogger.debug("Signature Received from " + quorumID[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]); - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", didHash); - detailsToVerify.put("hash", hash); - detailsToVerify.put("signature", qResponse[j]); - if (Authenticate.verifySignature(detailsToVerify.toString())) { - boolean voteStatus = voteNCount(index, quorumSize); - if (quorumResponse[index] <= minQuorum(quorumSize) && voteStatus) { - while (quorumResponse[index] < minQuorum(quorumSize)) { - } - 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); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); - } else { - - qOut[j].println("null"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); - } - BlockCommitInitiatorLogger.debug("Quorum Count : " + quorumResponse - + "Signature count : " + quorumSignature.length()); - } else { - BlockCommitInitiatorLogger.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]); - } - } - } - } catch (IOException | JSONException e) { - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); - BlockCommitInitiatorLogger.error("IOException Occurred"); - e.printStackTrace(); - } - }); - quorumThreads[j].start(); - } - - while (quorumResponse[index] < minQuorum(quorumSize) - || quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { - } - repo(ipfs); - - } catch (JSONException e) { - BlockCommitInitiatorLogger.error("JSON Exception Occurred", e); - e.printStackTrace(); - } - return quorumSignature; - } -} diff --git a/src/com/rubix/DataConsensus/BlockCommitProcedure.java b/src/com/rubix/DataConsensus/BlockCommitProcedure.java deleted file mode 100644 index 4a08bd45..00000000 --- a/src/com/rubix/DataConsensus/BlockCommitProcedure.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.rubix.DataConsensus; - -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 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; - -public class BlockCommitProcedure { - public static String essential; - public static String senderSignQ; - public static JSONObject payload = new JSONObject(); - public static JSONObject alphaReply, betaReply, gammaReply; - - public static Logger BlockCommitProcedureLogger = Logger.getLogger(BlockCommitProcedure.class); - - /** - * 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 { - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - - JSONObject dataObject = new JSONObject(data); - String tid = dataObject.getString("tid"); - String message = dataObject.getString("message"); - String blockHash = dataObject.getString("blockHash"); - 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(blockHash), "SHA3-256"); - - try { - payload.put("sender", senderDidIpfs); - // payload.put("token", token); - payload.put("blockHash", blockHash); - payload.put("tid", tid); - } catch (JSONException e) { - BlockCommitProcedureLogger.error("JSON Exception occurred", e); - e.printStackTrace(); - } - - Split.split(payload.toString()); - - int[][] shares = Split.get135Shares(); - BlockCommitProcedureLogger.debug("Payload Split Success"); - - JSONObject data1 = new JSONObject(); - JSONObject data2 = new JSONObject(); - - try { - - 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); - - BlockCommitProcedureLogger.error("Created Shares Q1 to Q4"); - - 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.TYPE, ConsensusConstants.RBD); - data1.put(ConsensusConstants.BLOCK, blockHash); - - data2.put("Share1", Q1Share); - data2.put("Share2", Q2Share); - data2.put("Share3", Q3Share); - data2.put("Share4", Q4Share); - } catch (JSONException | IOException e) { - BlockCommitProcedureLogger.error("JSON Exception occurred at getSignFromShares", e); - e.printStackTrace(); - - } - - JSONArray detailsForQuorum = new JSONArray(); - detailsForQuorum.put(data1); - detailsForQuorum.put(data2); - - BlockCommitProcedureLogger.debug("Invoking Consensus"); - - JSONObject dataSend = new JSONObject(); - dataSend.put("hash", authQuorumHash); - dataSend.put("details", detailsForQuorum); - - Thread alphaThread = new Thread(() -> { - try { - alphaReply = BlockCommitInitiator.start(dataSend.toString(), ipfs, PORT, 0, "alpha", alphaList, alphaSize, - alphaSize); - } catch (JSONException e) { - e.printStackTrace(); - } - }); - - Thread betaThread = new Thread(() -> { - try { - betaReply = BlockCommitInitiator.start(dataSend.toString(), ipfs, PORT + 100, 1, "beta", betaList, - alphaSize, 7); - } catch (JSONException e) { - e.printStackTrace(); - } - }); - - Thread gammaThread = new Thread(() -> { - try { - gammaReply = BlockCommitInitiator.start(dataSend.toString(), ipfs, PORT + 107, 2, "gamma", gammaList, - alphaSize, 7); - } catch (JSONException e) { - e.printStackTrace(); - } - }); - - BlockCommitInitiator.quorumSignature = new JSONObject(); - alphaThread.start(); - betaThread.start(); - gammaThread.start(); - while (BlockCommitInitiator.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { - } - BlockCommitProcedureLogger - .debug("ABG Consensus completed with length " + BlockCommitInitiator.quorumSignature.length()); - } -} diff --git a/src/com/rubix/DataConsensus/BlockCommitQuorum.java b/src/com/rubix/DataConsensus/BlockCommitQuorum.java deleted file mode 100644 index a661d74b..00000000 --- a/src/com/rubix/DataConsensus/BlockCommitQuorum.java +++ /dev/null @@ -1,301 +0,0 @@ -// package com.rubix.DataConsensus; - -// 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.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.listen; - -// 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.Constants.ConsensusConstants; -// import com.rubix.Resources.IPFSNetwork; - -// 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; - -// public class BlockCommitQuorum implements Runnable { - -// public static Logger BlockCommitQuorumLogger = -// Logger.getLogger(BlockCommitQuorum.class); - -// /** -// * This method is used to run a thread for Quorum Members -// *

-// * This involves -// *

    -// *
  1. Verify sender signature
  2. -// *
  3. Signing the transaction
  4. -// *
  5. Receiving share from sender
  6. -// *
-// */ - -// int port; -// IPFS ipfs; -// String role; -// int round; - -// public BlockCommitQuorum(String role, int port) { -// this.role = role; -// this.port = 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, blockHash, receiverPID, -// appName, senderPrivatePos, -// senderDidIpfsHash = "", senderPID = ""; -// ServerSocket serverSocket = null; -// Socket socket = null; -// try { - -// peerID = getPeerID(DATA_PATH + "DID.json"); -// String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", -// peerID); -// appName = peerID.concat(role); - -// listen(appName, port); - -// BlockCommitQuorumLogger.debug("Quorum Listening on " + port + " appname " + -// appName); -// serverSocket = new ServerSocket(port); -// socket = serverSocket.accept(); - -// BufferedReader in = new BufferedReader(new -// InputStreamReader(socket.getInputStream())); -// PrintStream out = new PrintStream(socket.getOutputStream()); - -// JSONObject readSenderData; -// String getData; - -// // ? check for incoming request for QST - -// // qstReq = dataReq.readLine(); -// // if (qstReq.contains("qstcmrequest")) { - -// // BlockCommitQuorumLogger -// // .debug("Sender reqesting QuorumSignedTransactions.json and -// // CreditMapping.json: " + qstReq); - -// // File creditsMapping = new File(WALLET_DATA_PATH + "CreditMapping.json"); -// // if (!creditsMapping.exists()) { -// // BlockCommitQuorumLogger.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); - -// // String cmFileHash = IPFSNetwork.add(WALLET_DATA_PATH + -// "CreditMapping.json", -// // ipfs); - -// // JSONObject qResponse = new JSONObject(); -// // qResponse.put("QuorumSignedTransactions", qstObjectSend.toString()); -// // qResponse.put("CreditMapping", cmFileHash); - -// // dataResp.println(qResponse.toString()); -// // } - -// // TODO: if the incoming request contains the keyword "request", push the QST -// to -// // IPFS and send the two hashes back to the sender. - -// // ? This is where quorum fetched the data send from initiatorConsensus (Line -// // 148) - -// getData = in.readLine(); -// if (getData.contains("ping check")) { -// BlockCommitQuorumLogger.debug("Ping check from sender: " + getData); -// out.println("pong response"); -// } else { -// BlockCommitQuorumLogger.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"); -// blockHash = readSenderData.getString(ConsensusConstants.BLOCK); - -// senderPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", -// senderDidIpfsHash); -// // receiverPID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", -// // blockHash); - -// String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", -// "walletHash", "didHash", -// senderDidIpfsHash); - -// nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); -// String quorumHash = calculateHash(verifySenderHash.concat(blockHash), -// "SHA3-256"); - -// JSONObject detailsToVerify = new JSONObject(); -// detailsToVerify.put("did", senderDidIpfsHash); -// detailsToVerify.put("hash", verifySenderHash); -// detailsToVerify.put("signature", senderPrivatePos); - -// // BlockCommitQuorumLogger.debug("Checking providers for: " + -// verifySenderHash); -// // ArrayList dhtOwnersList = dhtOwnerCheck(verifySenderHash); -// // BlockCommitQuorumLogger.debug("Providers: " + dhtOwnersList); -// // boolean consensusIDcheck = true; -// // 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"); - -// // TODO: check minimum balance of sender is one RBT - -// // TODO: verifying the block hash, fetching block hash and pinning files in -// // block file. -// if (Authenticate.verifySignature(detailsToVerify.toString())) { -// BlockCommitQuorumLogger.debug("Quorum Authenticated Sender"); - -// IPFSNetwork.pin(blockHash, ipfs); - -// pinBlockFiles(blockHash, ipfs); -// String QuorumSignature = getSignFromShares(DATA_PATH + didHash + -// "/PrivateShare.png", -// quorumHash); -// out.println(QuorumSignature); -// String creditval; -// creditval = in.readLine(); -// BlockCommitQuorumLogger.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); - -// } - -// JSONObject storeDetailsQuorum = new JSONObject(); -// storeDetailsQuorum.put("tid", transactionID); -// storeDetailsQuorum.put("consensusID", verifySenderHash); -// storeDetailsQuorum.put("sign", senderPrivatePos); -// storeDetailsQuorum.put("credits", credit); -// storeDetailsQuorum.put("senderdid", senderDidIpfsHash); - -// // ? During mining if QST file has blockHash instead of recieverID, then -// credit -// // is counted as 2 for that transaction. -// storeDetailsQuorum.put("blockHash", blockHash); - -// JSONArray data = new JSONArray(); -// data.put(storeDetailsQuorum); -// BlockCommitQuorumLogger.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"); -// BlockCommitQuorumLogger.debug("added consensus ID " + consenusIDhash); -// } -// } else { -// BlockCommitQuorumLogger.debug("Sender Authentication Failure - Quorum"); -// out.println("Auth_Failed"); -// } -// } -// } catch (IOException e) { -// BlockCommitQuorumLogger.error("IOException Occurred", e); -// } catch (JSONException e) { -// BlockCommitQuorumLogger.error("JSONException Occurred", e); -// } catch (NullPointerException e) { -// BlockCommitQuorumLogger.error("NullPointer Exception Occurred ", e); -// } - -// finally { -// try { -// socket.close(); -// serverSocket.close(); -// executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); -// } catch (IOException e) { -// executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); -// BlockCommitQuorumLogger.error("IOException Occurred", e); -// } - -// } -// } - -// } - -// private void pinBlockFiles(String blockHash, IPFS ipfs) throws JSONException -// { -// 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); -// } - -// } -// } diff --git a/src/com/rubix/DataConsensus/QuorumPinning.java b/src/com/rubix/DataConsensus/QuorumPinning.java deleted file mode 100644 index 4ccde6fd..00000000 --- a/src/com/rubix/DataConsensus/QuorumPinning.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.rubix.DataConsensus; - -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.updateJSON; -import static com.rubix.Resources.Functions.writeToFile; -import static com.rubix.Resources.IPFSNetwork.add; -import static com.rubix.Resources.IPFSNetwork.listen; - -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.Constants.ConsensusConstants; -import com.rubix.Resources.IPFSNetwork; - -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.json.JSONArray; -import org.json.JSONObject; - -import io.ipfs.api.IPFS; - -public class QuorumPinning implements Runnable { - - public static Logger QuorumPinningLogger = Logger.getLogger(QuorumPinning.class); - - int port; - IPFS ipfs; - String role; - int round; - - public QuorumPinning(String role, int port) { - this.role = role; - this.port = 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"); - String peerID, appName; - ServerSocket serverSocket = null; - Socket socket = null; - - try { - - peerID = getPeerID(DATA_PATH + "DID.json"); - String didHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID); - appName = peerID.concat(role); - - listen(appName, port); - - QuorumPinningLogger.debug("Quorum Listening on " + port + " appname " + appName); - serverSocket = new ServerSocket(port); - socket = serverSocket.accept(); - - BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - PrintStream out = new PrintStream(socket.getOutputStream()); - - Thread validate = new SenderHandler(socket, in, out, ipfs, peerID, didHash, appName); - validate.start(); - - } catch (IOException e) { - QuorumPinningLogger.error("Error in QuorumPinning: " + e.getMessage()); - } - - } - } -} - -class SenderHandler extends Thread { - - public static Logger SenderHandlerLogger = Logger.getLogger(SenderHandler.class); - - final Socket socket; - final BufferedReader in; - final PrintStream out; - final IPFS ipfs; - final String peerID; - final String didHash; - final String appName; - - public SenderHandler(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(); - } - - boolean integrityCheck = true; - String temp = ""; - String transactionID = ""; - String verifySenderHash = ""; - String blockHash = ""; - String senderPrivatePos = ""; - String senderDidIpfsHash = ""; - String senderPID = ""; - String getData; - - JSONObject readSenderData; - - public void run() { - - while (true) { - try { - getData = in.readLine(); - - if (getData.contains("ping check")) { - SenderHandlerLogger.debug("Ping check from sender: " + getData); - out.println("pong response"); - } else { - SenderHandlerLogger.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"); - blockHash = readSenderData.getString(ConsensusConstants.BLOCK); - - 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(blockHash), "SHA3-256"); - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", senderDidIpfsHash); - detailsToVerify.put("hash", verifySenderHash); - detailsToVerify.put("signature", senderPrivatePos); - - if (Authenticate.verifySignature(detailsToVerify.toString())) { - SenderHandlerLogger.debug("Quorum Authenticated 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); - } - - String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - quorumHash); - out.println(QuorumSignature); - String creditval; - creditval = in.readLine(); - SenderHandlerLogger.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); - - } - - 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); - SenderHandlerLogger.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"); - SenderHandlerLogger.debug("added consensus ID " + consenusIDhash); - } - } else { - SenderHandlerLogger.debug("Sender Authentication Failure - Quorum"); - out.println("Auth_Failed"); - } - } - } catch (Exception e) { - SenderHandlerLogger.error("Exception in SenderHandler: " + e); - } - } - } - -} \ No newline at end of file diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index d9170598..9ae76b0d 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -1,5 +1,6 @@ package com.rubix.TokenTransfer; +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; @@ -672,6 +673,510 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } + if (detailsObject.getString(TRANS_TYPE) == DATA) { + + String blockHash = detailsObject.getString("blockHash"); + int amount = detailsObject.getInt("amount"); + JSONArray tokenHeader = detailsObject.getJSONArray("tokenHeader"); + + 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); + + 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 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; + + } + } + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + eventLogger.debug("Get Quorum List " + totalTime); + + startTime = System.currentTimeMillis(); + QuorumSwarmConnect(quorumArray, ipfs); + endTime = System.currentTimeMillis(); + totalTime = endTime - startTime; + eventLogger.debug("Swarm Connect " + totalTime); + + 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)); + } + + 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; + + } + + 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", "Success"); + APIResponse.put("did", senderDidIpfsHash); + 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()); + + 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; return APIResponse; From a72927e18fbac21c50d353663e4bd01fe78c9f61 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 31 Dec 2021 12:02:30 +0530 Subject: [PATCH 10/11] Fix needed: TYPE response error Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Resources/APIHandler.java | 19 ++++--------------- src/com/rubix/TokenTransfer/TokenSender.java | 8 ++++++++ 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index ac8245d7..b2b0af27 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -1,7 +1,7 @@ package com.rubix.Resources; +import static com.rubix.Constants.ConsensusConstants.DATA; import static com.rubix.Constants.ConsensusConstants.PRIMARY; -import static com.rubix.Constants.ConsensusConstants.SECONDARY; import static com.rubix.Constants.ConsensusConstants.TRANS_TYPE; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.IPFS_PORT; @@ -75,11 +75,9 @@ public static JSONObject send(String data) throws Exception { String recDID; String blockHash; JSONArray tokens; - JSONObject dataObject = new JSONObject(data); - // check if receiverDidIpfsHash is present in the dataObject - if (dataObject.has("receiverDidIpfsHash") && dataObject.has("tokens")) { + if (dataObject.has("receiverDidIpfsHash")) { dataObject.put(TRANS_TYPE, PRIMARY); @@ -113,7 +111,7 @@ public static JSONObject send(String data) throws Exception { } else if (dataObject.has("blockHash")) { - dataObject.put(TRANS_TYPE, SECONDARY); + dataObject.put(TRANS_TYPE, DATA); blockHash = dataObject.getString("blockHash"); if (blockHash.length() != 46) { @@ -133,17 +131,8 @@ public static JSONObject send(String data) throws Exception { } - // String comments = dataObject.getString("comments"); - // JSONArray tokenHeader = dataObject.getJSONArray("tokenHeader"); - // int amount = dataObject.getInt("amount"); - - // 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"); + APILogger.info("Initiating transaction for:" + dataObject.toString()); sendMessage = TokenSender.Send(dataObject.toString(), ipfs, SEND_PORT); APILogger.info(sendMessage); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 9ae76b0d..7ac8febe 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -172,12 +172,20 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception allTokensChainsPushed.add(tokenChainHash); } + TokenSenderLogger.debug("All tokens added"); + // 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; } + TokenSenderLogger.debug("Initiating transaction type:" + detailsObject.has(TRANS_TYPE)); + if (detailsObject.getString(TRANS_TYPE) == PRIMARY) { String receiverDidIpfsHash = detailsObject.getString("receiverDidIpfsHash"); From 895aee8b3c3abd7c296becec26ac23164cfdf2bb Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sat, 8 Jan 2022 10:33:09 +0530 Subject: [PATCH 11/11] update gitignore Signed-off-by: Nidhin Mahesh A --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) 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