From a97b9bb29d4d11a8a107bca18a709c2dd994ddd8 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 18 Feb 2022 12:36:37 +0530 Subject: [PATCH 001/179] reciever checks Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 149 +++++----- src/com/rubix/Consensus/QuorumConsensus.java | 35 +-- src/com/rubix/Resources/Functions.java | 64 +++++ src/com/rubix/Resources/IPFSNetwork.java | 268 ++++++++++-------- .../rubix/TokenTransfer/TokenReceiver.java | 86 ++++-- 5 files changed, 351 insertions(+), 251 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index d030dcfa..162371cd 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -3,7 +3,6 @@ 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.checkTokenOwnershiByDID; import static com.rubix.Resources.Functions.getValues; import static com.rubix.Resources.Functions.minQuorum; import static com.rubix.Resources.Functions.nodeData; @@ -13,7 +12,6 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; @@ -22,7 +20,6 @@ import java.util.ArrayList; import com.rubix.AuthenticateNode.Authenticate; -import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; import org.apache.log4j.Logger; @@ -356,78 +353,80 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri quorumThreads[j].start(); } - if (operation.equals("new-credits-mining")) { - Thread[] stakingThreads = new Thread[signedAlphaQuorumID.length]; - // ? one of the validators stake 1 RBT and send the stake ID to the miner. - // choose a quorum member from 1 to 5 who have signed the transaction - for (int p = 0; p < signedAlphaQuorumID.length; p++) { - int s = p; - stakingThreads[p] = new Thread(() -> { - try { - InitiatorConsensusLogger.debug( - "Contacting Signed Alpha Quorum ID : " + signedAlphaQuorumID[s] - + " for staking. Index " - + s); - - qSocket[s] = new Socket("127.0.0.1", PORT + s); - qSocket[s].setSoTimeout(socketTimeOut); - qIn[s] = new BufferedReader(new InputStreamReader(qSocket[s].getInputStream())); - qOut[s] = new PrintStream(qSocket[s].getOutputStream()); - - qOut[s].println("stake-token"); - try { - qResponse[s] = qIn[s].readLine(); - String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", - "peerid", signedAlphaQuorumID[s]); - if (checkTokenOwnershiByDID(qResponse[s], stakingQuorumDID)) { - if (true) { - - // ! generate stake ID and send to staking quorum - - InitiatorConsensusLogger.debug("Staking Successful at index " + s); - } else { - - InitiatorConsensusLogger.debug("sending null for slow quorum "); - qOut[s].println("null"); - IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); - - } - - } else { - - InitiatorConsensusLogger.debug("sending null for slow quorum "); - qOut[s].println("null"); - IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); - - } - } catch (SocketException e) { - InitiatorConsensusLogger - .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumID[s] - + " is unable to Respond!"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); - } - - } catch (Exception e) { - InitiatorConsensusLogger.error("Exception Occurred"); - e.printStackTrace(); - } - }); - stakingThreads[s].start(); - } - // check the balance - // if balance is sufficient then stake the token - // else send a null to Qa(j) - // if Qa(j) sends a null then close the connection - // else send the stake ID to Qa(j) - // pin the stake ID (initiator) and keep it in a file for future use - File stakesFolder = new File(Functions.WALLET_DATA_PATH.concat("/Stakes")); - if (!stakesFolder.exists()) - stakesFolder.mkdirs(); - // send mining fee to Qa(j) - 0.02 RBT - // close the connection - } + // if (operation.equals("new-credits-mining")) { + // Thread[] stakingThreads = new Thread[signedAlphaQuorumID.length]; + // // ? one of the validators stake 1 RBT and send the stake ID to the miner. + // // choose a quorum member from 1 to 5 who have signed the transaction + // for (int p = 0; p < signedAlphaQuorumID.length; p++) { + // int s = p; + // stakingThreads[p] = new Thread(() -> { + // try { + // InitiatorConsensusLogger.debug( + // "Contacting Signed Alpha Quorum ID : " + signedAlphaQuorumID[s] + // + " for staking. Index " + // + s); + + // qSocket[s] = new Socket("127.0.0.1", PORT + s); + // qSocket[s].setSoTimeout(socketTimeOut); + // qIn[s] = new BufferedReader(new + // InputStreamReader(qSocket[s].getInputStream())); + // qOut[s] = new PrintStream(qSocket[s].getOutputStream()); + + // qOut[s].println("stake-token"); + // try { + // qResponse[s] = qIn[s].readLine(); + // String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", + // "peerid", signedAlphaQuorumID[s]); + // if (checkTokenOwnershiByDID(qResponse[s], stakingQuorumDID)) { + // if (true) { + + // // ! generate stake ID and send to staking quorum + + // InitiatorConsensusLogger.debug("Staking Successful at index " + s); + // } else { + + // InitiatorConsensusLogger.debug("sending null for slow quorum "); + // qOut[s].println("null"); + // IPFSNetwork.executeIPFSCommands( + // "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); + + // } + + // } else { + + // InitiatorConsensusLogger.debug("sending null for slow quorum "); + // qOut[s].println("null"); + // IPFSNetwork.executeIPFSCommands( + // "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); + + // } + // } catch (SocketException e) { + // InitiatorConsensusLogger + // .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumID[s] + // + " is unable to Respond!"); + // IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + + // signedAlphaQuorumID[s]); + // } + + // } catch (Exception e) { + // InitiatorConsensusLogger.error("Exception Occurred"); + // e.printStackTrace(); + // } + // }); + // stakingThreads[s].start(); + // } + // // check the balance + // // if balance is sufficient then stake the token + // // else send a null to Qa(j) + // // if Qa(j) sends a null then close the connection + // // else send the stake ID to Qa(j) + // // pin the stake ID (initiator) and keep it in a file for future use + // File stakesFolder = new File(Functions.WALLET_DATA_PATH.concat("/Stakes")); + // if (!stakesFolder.exists()) + // stakesFolder.mkdirs(); + // // send mining fee to Qa(j) - 0.02 RBT + // // close the connection + // } while (quorumResponse[index] < minQuorum(quorumSize) || quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index f581e1d3..967751c2 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -108,28 +108,6 @@ public void run() { executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - if (operation.equals("stake-token")) { - - String stakeDetails; - - // ! send token ID choosen - out.println("null"); - - try { - stakeDetails = in.readLine(); - } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - New stake ID Details"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - JSONObject stakeDetailsJSON = new JSONObject(stakeDetails); - generateStakeIDByToken(stakeDetailsJSON.getString("stakeID"), stakeDetailsJSON.getString("minedToken")); - out.println("OK") - // ! wait for 0.02 RBT - - } - if (operation.equals("new-credits-mining")) { QuorumConsensusLogger.debug("New Credits"); @@ -259,10 +237,6 @@ public void run() { // ! additional info for the mining verification initHash = readSenderData.getString("initHash"); token = readSenderData.getString("token"); - stakedToken = readSenderData.getString("stakedToken"); - String stakingQuorumPeerID = readSenderData.getString("stakingQuorumPeerID"); - stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", - stakingQuorumPeerID); // ! match initiator initHash with quorum. if didn't match, reject @@ -286,8 +260,7 @@ public void run() { // sender + receiver hash) // concat of sender hash and rec hash) - String quorumHash = calculateHash(token + transactionID + stakingQuorumDID, "SHA3-256"); - String stakeHash = calculateHash(token + stakedToken, "SHA3-256"); + String quorumHash = calculateHash(token + transactionID, "SHA3-256"); QuorumConsensusLogger.debug("1: " + verifySenderHash); QuorumConsensusLogger.debug("2: " + receiverDID); @@ -329,11 +302,11 @@ public void run() { quorumSigns.put("TokenSign", QuorumSignatureTwo); // ! 3th sign: Token + TID - String QuorumSignatureFive = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + String QuorumSignatureThree = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", quorumHash); - quorumSigns.put("QuorumSign", QuorumSignatureFive); + quorumSigns.put("QuorumSign", QuorumSignatureThree); - out.println(quorumSigns); + out.println(quorumSigns.toString()); String creditSignatures = null; try { diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index e03ff34c..f490d84e 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -454,6 +454,70 @@ public static boolean checkTokenOwnershiByDID(String tokenID, String DID) { return ownStatus; } + /** + * This function generate Stake ID for a pleadged token. mined token can also be + * found from stake ID + * + * @param token ID to be staked + * @return Stake ID for that token + */ + public static String generateStakeID(String stakedTokenID) { + String stakeID = calculateHash("stake" + stakedTokenID, "SHA3-256"); + return stakeID; + } + + /** + * This function generate Stake ID for a pleadged token. mined token can also be + * found from stake ID + * + * @param token ID to be staked + * @return Stake ID for that token + */ + public static String minedTokenIDFromStakeID(String stakeID) { + // ! multihash structure needed.. + String minedTokenID = calculateHash("stake" + stakeID, "SHA3-256"); + return minedTokenID; + } + + /** + * This function generate Stake ID for a pleadged token. mined token can also be + * found from stake ID + * + * @param token ID to be staked + * @return Stake ID for that token + */ + public static int tokenHeightFromTokenID(String tokenID) { + + int tokenChainLength = 32; + + // ! get data from DID server or contact owner of mined token for token height + + return tokenChainLength; + } + + /** + * This function check Stake ID for a pleadged token. mined token can also be + * found from stake ID + * + * @param token ID to be staked + * @return boolean of exists or not + */ + public static boolean checkStakeIDExists(String tokenID) { + boolean stakeIDExists = false; + String stakeID = calculateHash("stake" + tokenID, "SHA3-256"); + stakeIDExists = checkTokenOwnershiByDID(stakeID, stakeID); + try { + ArrayList owners = dhtOwnerCheck(tokenID); + if (!owners.isEmpty()) { + stakeIDExists = true; + } + + } catch (InterruptedException | JSONException | IOException e) { + FunctionsLogger.error("JSONException Occurred while - checkStakeIDExists - check", e); + } + return stakeIDExists; + } + /** * This function converts any integer to its binary form * diff --git a/src/com/rubix/Resources/IPFSNetwork.java b/src/com/rubix/Resources/IPFSNetwork.java index 2921d551..e7b90ead 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 @@ -365,7 +382,6 @@ public static ArrayList dhtOwnerCheck(String objectHash) throws InterruptedExcep commands[2] = "ipfs dht findprovs " + objectHash; } - ProcessBuilder p = new ProcessBuilder(commands); Process process = p.start(); @@ -378,7 +394,6 @@ public static ArrayList dhtOwnerCheck(String objectHash) throws InterruptedExcep array.add(line); process.waitFor(); - return array; } @@ -452,7 +467,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(); @@ -560,22 +576,22 @@ public static void swarmConnectP2P(String peerid, IPFS ipfs) throws JSONExceptio if (!swarmConnected) { bootNode = String.valueOf(BOOTSTRAPS.get(i)); bootNode = bootNode.substring(bootNode.length() - 46); - + multiAddress = new MultiAddress("/ipfs/" + bootNode); output = swarmConnectProcess(multiAddress); - + 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; - } + 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 { - IPFSNetworkLogger.debug("bootstrap connection failed! " + bootNode); - } + IPFSNetworkLogger.debug("bootstrap connection failed! " + bootNode); + } } } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 3707abf2..4d0aeae7 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -203,8 +203,11 @@ public static String receive() { int intPart = wholeTokens.length(); Double decimalPart = formatAmount(amount - intPart); JSONArray doubleSpentToken = new JSONArray(); + JSONArray stakedToken = new JSONArray(); boolean tokenOwners = true; + boolean incompleteStake = false; ArrayList ownersArray = new ArrayList(); + ArrayList stakeOwnersArray = new ArrayList(); ArrayList previousSender = new ArrayList(); JSONArray ownersReceived = new JSONArray(); for (int i = 0; i < wholeTokens.length(); ++i) { @@ -232,9 +235,10 @@ public static String receive() { } } catch (IOException e) { - TokenReceiverLogger.debug("Ipfs dht find did not execute"); + TokenReceiverLogger.trace("Ipfs dht find did not execute (double spend check)"); } } + if (!tokenOwners) { JSONArray owners = new JSONArray(); for (int i = 0; i < ownersArray.size(); i++) @@ -256,6 +260,67 @@ public static String receive() { return APIResponse.toString(); } + // ! starts stakeID checks + + for (int i = 0; i < wholeTokens.length(); ++i) { + try { + TokenReceiverLogger.debug("Checking stake ID for " + wholeTokens.getString(i) + " Please wait..."); + String stakeID = Functions.generateStakeID(tokenDetails); + stakeOwnersArray = IPFSNetwork.dhtOwnerCheck(stakeID); + + if (stakeOwnersArray.size() > 1) { + + // ! check sign on pinned stake ID + + String minedToken = Functions.minedTokenIDFromStakeID(stakeID); + + int minedTokenHeight = Functions.tokenHeightFromTokenID(minedToken); + if (minedTokenHeight < 32) { + incompleteStake = true; + } + + // for (int j = 0; j < previousSendersArray.length(); j++) { + // if (previousSendersArray.getJSONObject(j).getString("token") + // .equals(wholeTokens.getString(i))) + // ownersReceived = + // previousSendersArray.getJSONObject(j).getJSONArray("sender"); + // } + + // for (int j = 0; j < ownersReceived.length(); j++) { + // previousSender.add(ownersReceived.getString(j)); + // } + // TokenReceiverLogger.debug("Previous Owners: " + previousSender); + + // for (int j = 0; j < ownersArray.size(); j++) { + // if (!previousSender.contains(ownersArray.get(j).toString())) + // tokenOwners = false; + // } + } + } catch (IOException e) { + + TokenReceiverLogger.trace("Ipfs dht find did not execute (stakeID check)"); + } + } + + if (incompleteStake) { + TokenReceiverLogger.debug("Token Height not reached for corresponding Staked Tokens " + stakedToken); + output.println("200"); + output.println(stakedToken.toString()); + output.println("stakes not complete"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Token Height not reached for corresponding Staked Tokens " + stakedToken); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + + // ! ends stakeID checks + String senderToken = TokenDetails.toString(); String consensusID = calculateHash(senderToken, "SHA3-256"); writeToFile(LOGGER_PATH + "consensusID", consensusID, false); @@ -277,8 +342,6 @@ public static String receive() { return APIResponse.toString(); } - // Check IPFS get and Stake ID (signed when participated as quorum in mining) - // for all Tokens int ipfsGetFlag = 0; ArrayList allTokenContent = new ArrayList<>(); ArrayList allTokenChainContent = new ArrayList<>(); @@ -287,22 +350,7 @@ public static String receive() { allTokenChainContent.add(TokenChainContent); String TokenContent = get(wholeTokens.getString(i), ipfs); - // ! yet to verify if we are going to use stake ID or quorum pinning token on - - // ? Steps - // ? generate stake ID for the token hash - // ? check if stake ID exists in the network for the token hash (someone must - // have staked this token for participating in mining) - // ? stake ID should be signed by the staking node to avoid malicious node - // staking tokens they dont own - // ? get mined token from stake ID - // ? if the mined token has token chain content > credits required to mine that - // token, then stake ID is not considered and token is accepted by reciever - // ? ignore the token and continue with the transaction - - allTokenContent.add(TokenContent); - ipfsGetFlag++; - } + repo(ipfs); if (!(ipfsGetFlag == intPart)) { From ffb4848b31da3e4f620de37294c952bb435f6d6a Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 18 Feb 2022 12:40:13 +0530 Subject: [PATCH 002/179] cleanup token rec Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 4d0aeae7..1e75a19e 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -342,6 +342,7 @@ public static String receive() { return APIResponse.toString(); } + // Check IPFS get for all Tokens int ipfsGetFlag = 0; ArrayList allTokenContent = new ArrayList<>(); ArrayList allTokenChainContent = new ArrayList<>(); @@ -349,8 +350,9 @@ public static String receive() { String TokenChainContent = get(wholeTokenChains.getString(i), ipfs); allTokenChainContent.add(TokenChainContent); String TokenContent = get(wholeTokens.getString(i), ipfs); - - + allTokenContent.add(TokenContent); + ipfsGetFlag++; + } repo(ipfs); if (!(ipfsGetFlag == intPart)) { @@ -419,6 +421,7 @@ public static String receive() { } } } + if (!chainFlag) { String errorMessage = "Broken Cheque Chain"; From ff351ee206b78210ca0948fc8678efdb3e9be206 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 22 Feb 2022 01:31:50 +0530 Subject: [PATCH 003/179] initiator checks Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 251 +++++++++++------- src/com/rubix/Consensus/QuorumConsensus.java | 107 ++++++++ src/com/rubix/Resources/Functions.java | 110 ++++++-- .../rubix/TokenTransfer/TokenReceiver.java | 12 +- 4 files changed, 362 insertions(+), 118 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 162371cd..9c94db13 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -3,15 +3,24 @@ 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.WALLET_DATA_PATH; +import static com.rubix.Resources.Functions.checkTokenOwnershiByDID; +import static com.rubix.Resources.Functions.creditsRequiredForLevel; +import static com.rubix.Resources.Functions.deleteFile; 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.syncDataTable; +import static com.rubix.Resources.Functions.writeToFile; +import static com.rubix.Resources.IPFSNetwork.add; import static com.rubix.Resources.IPFSNetwork.forward; +import static com.rubix.Resources.IPFSNetwork.pin; import static com.rubix.Resources.IPFSNetwork.repo; import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import java.io.BufferedReader; +import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; @@ -70,22 +79,23 @@ private static synchronized boolean voteNCount(int i, int quorumSize) { /** * This method increments the quorumResponse variable */ - private static synchronized boolean selectStakingQuorum(String DID) { - boolean status; - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - synchronized (countLock) { - if (quorumResponse[i] < minQuorum(quorumSize)) { - quorumResponse[i]++; - InitiatorConsensusLogger.debug("quorum response added index " + i + " is " + quorumResponse[i] - + " quorumsize " + minQuorum(quorumSize)); - status = true; - } else { - status = false; - InitiatorConsensusLogger.debug("Staking Reached"); - } - } - return status; - } + // private static synchronized boolean selectStakingQuorum(String DID) { + // boolean status; + // PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + // synchronized (countLock) { + // if (quorumResponse[i] < minQuorum(quorumSize)) { + // quorumResponse[i]++; + // InitiatorConsensusLogger.debug("quorum response added index " + i + " is " + + // quorumResponse[i] + // + " quorumsize " + minQuorum(quorumSize)); + // status = true; + // } else { + // status = false; + // InitiatorConsensusLogger.debug("Staking Reached"); + // } + // } + // return status; + // } /** * This method stores all the quorum signatures until required count for @@ -196,8 +206,6 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (qResponse[j] != null) { if (qResponse[j].equals("Verified")) { - // ! let all quorum mems know who is staking and use it in signature - detailsToken.put("stakingQuorumPeerID", quorumID[0]); qOut[j].println(detailsToken); try { qResponse[j] = qIn[j].readLine(); @@ -353,80 +361,139 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri quorumThreads[j].start(); } - // if (operation.equals("new-credits-mining")) { - // Thread[] stakingThreads = new Thread[signedAlphaQuorumID.length]; - // // ? one of the validators stake 1 RBT and send the stake ID to the miner. - // // choose a quorum member from 1 to 5 who have signed the transaction - // for (int p = 0; p < signedAlphaQuorumID.length; p++) { - // int s = p; - // stakingThreads[p] = new Thread(() -> { - // try { - // InitiatorConsensusLogger.debug( - // "Contacting Signed Alpha Quorum ID : " + signedAlphaQuorumID[s] - // + " for staking. Index " - // + s); - - // qSocket[s] = new Socket("127.0.0.1", PORT + s); - // qSocket[s].setSoTimeout(socketTimeOut); - // qIn[s] = new BufferedReader(new - // InputStreamReader(qSocket[s].getInputStream())); - // qOut[s] = new PrintStream(qSocket[s].getOutputStream()); - - // qOut[s].println("stake-token"); - // try { - // qResponse[s] = qIn[s].readLine(); - // String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", - // "peerid", signedAlphaQuorumID[s]); - // if (checkTokenOwnershiByDID(qResponse[s], stakingQuorumDID)) { - // if (true) { - - // // ! generate stake ID and send to staking quorum - - // InitiatorConsensusLogger.debug("Staking Successful at index " + s); - // } else { - - // InitiatorConsensusLogger.debug("sending null for slow quorum "); - // qOut[s].println("null"); - // IPFSNetwork.executeIPFSCommands( - // "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); - - // } - - // } else { - - // InitiatorConsensusLogger.debug("sending null for slow quorum "); - // qOut[s].println("null"); - // IPFSNetwork.executeIPFSCommands( - // "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); - - // } - // } catch (SocketException e) { - // InitiatorConsensusLogger - // .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumID[s] - // + " is unable to Respond!"); - // IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + - // signedAlphaQuorumID[s]); - // } - - // } catch (Exception e) { - // InitiatorConsensusLogger.error("Exception Occurred"); - // e.printStackTrace(); - // } - // }); - // stakingThreads[s].start(); - // } - // // check the balance - // // if balance is sufficient then stake the token - // // else send a null to Qa(j) - // // if Qa(j) sends a null then close the connection - // // else send the stake ID to Qa(j) - // // pin the stake ID (initiator) and keep it in a file for future use - // File stakesFolder = new File(Functions.WALLET_DATA_PATH.concat("/Stakes")); - // if (!stakesFolder.exists()) - // stakesFolder.mkdirs(); - // // send mining fee to Qa(j) - 0.02 RBT - // // close the connection - // } + if (operation.equals("new-credits-mining")) { + + Thread[] stakingThreads = new Thread[signedAlphaQuorumID.length]; + // ? one of the validators stake 1 RBT and send the stake ID to the miner. + // choose a quorum member from 1 to 5 who have signed the transaction + for (int p = 0; p < signedAlphaQuorumID.length; p++) { + int s = p; + stakingThreads[p] = new Thread(() -> { + try { + InitiatorConsensusLogger.debug( + "Contacting Signed Alpha Quorum ID : " + signedAlphaQuorumID[s] + + " for staking. Index " + + s); + + qSocket[s] = new Socket("127.0.0.1", PORT + s); + qSocket[s].setSoTimeout(socketTimeOut); + qIn[s] = new BufferedReader(new InputStreamReader(qSocket[s].getInputStream())); + qOut[s] = new PrintStream(qSocket[s].getOutputStream()); + + qOut[s].println("stake-token"); + try { + + qResponse[s] = qIn[s].readLine(); + // convert to JSON array + JSONArray stakingTokenDetals = new JSONArray(qResponse[s]); + // get token chain and token ID from the array + String tokenID = stakingTokenDetals.getString(0); + JSONArray tokenChain = stakingTokenDetals.getJSONArray(1); + + String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", + "peerid", signedAlphaQuorumID[s]); + if (checkTokenOwnershiByDID(tokenID, stakingQuorumDID) + && tokenChain.length() > creditsRequiredForLevel()) { + + InitiatorConsensusLogger.debug("Staking Token Received and Verified from " + + signedAlphaQuorumID[s] + " " + qResponse[s]); + + String mineID = "1234caf17ff4d84f8614091bf222c03ed43d0bd5f2ee75c1814372c62xxxxx"; + InitiatorConsensusLogger.debug("Sending mine ID to miner " + mineID); + qOut[s].println(mineID); + + try { + qResponse[s] = qIn[s].readLine(); + InitiatorConsensusLogger.debug("Signature for Mining ID Received from " + + signedAlphaQuorumID[s] + " " + qResponse[s]); + } catch (SocketException e) { + InitiatorConsensusLogger + .warn("Quorum " + quorumID[s] + " is unable to Respond!"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); + } + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakingQuorumDID); + detailsToVerify.put("hash", mineID); + detailsToVerify.put("signature", qResponse[s]); + + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mineID.txt"), + true); + shareWriter.write(qResponse[s]); + shareWriter.close(); + File readMineID = new File(LOGGER_PATH + "mineID.txt"); + String mineData = add(readMineID.toString(), ipfs); + pin(mineData, ipfs); + + File mineIDFile = new File( + WALLET_DATA_PATH.concat("/Stakes/").concat(mineData).concat(".json")); + if (!mineIDFile.exists()) + mineIDFile.createNewFile(); + writeToFile(mineIDFile.toString(), qResponse[s], false); + + InitiatorConsensusLogger.debug("Mine object: " + mineData); + deleteFile(LOGGER_PATH + "mineID.txt"); + + InitiatorConsensusLogger.debug("Staking Successful at index " + s); + + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); + + JSONObject stakingInfo = new JSONObject(); + stakingInfo.put("StakerDID", stakingQuorumDID); + stakingInfo.put("StakedokenID", tokenID); + stakingInfo.put("minedToken", detailsToken); + + JSONArray creditArray = new JSONArray(); + creditArray.put(finalQuorumSignsArray); + + qOut[s].println(creditArray); + + } else { + + InitiatorConsensusLogger.debug("sending null for slow quorum "); + qOut[s].println("null"); + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); + + } + + } else { + + InitiatorConsensusLogger.debug("sending null for slow quorum "); + qOut[s].println("null"); + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); + + } + } catch (SocketException e) { + InitiatorConsensusLogger + .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumID[s] + + " is unable to Respond!"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + + signedAlphaQuorumID[s]); + } + + } catch (Exception e) { + InitiatorConsensusLogger.error("Exception Occurred"); + e.printStackTrace(); + } + }); + stakingThreads[s].start(); + } + // check the balance + // if balance is sufficient then stake the token + // else send a null to Qa(j) + // if Qa(j) sends a null then close the connection + // else send the stake ID to Qa(j) + // pin the stake ID (initiator) and keep it in a file for future use + File stakesFolder = new File(WALLET_DATA_PATH.concat("/Stakes")); + if (!stakesFolder.exists()) + stakesFolder.mkdirs(); + // send mining fee to Qa(j) - 0.02 RBT + // close the connection + } while (quorumResponse[index] < minQuorum(quorumSize) || quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 967751c2..6565012e 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -210,6 +210,113 @@ public void run() { } else QuorumConsensusLogger.debug("Old Credits Mining / Whole RBT Token Transfer"); + // ! operation for quorum staking token starts here + + if (operation.equals("stake-token")) { + + QuorumConsensusLogger.debug("Staking Credits"); + String getNewCreditsData = null; + String tokenToStake = null; + // move that token ID to bottom of BNK00 file + try { + getNewCreditsData = in.readLine(); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - Stake ID details"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + // Verify QST Credits + JSONObject qstObject = new JSONObject(getNewCreditsData); + + // Get level of token from advisory node + int creditsRequired = 0; + JSONObject resJsonData_credit = new JSONObject(); + String GET_URL_credit = SYNC_IP + "/getlevel"; + URL URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + QuorumConsensusLogger.debug("response from service " + response_credit.toString()); + resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + creditsRequired = (int) Math.pow(2, (2 + level_credit)); + QuorumConsensusLogger.debug("credits required " + creditsRequired); + + } else + QuorumConsensusLogger.debug("Advisory GET request not worked"); + + // Level 1 Verification: Verify hash of n objects + JSONArray qstArray = qstObject.getJSONArray("qstArray"); + JSONArray creditsArray = qstObject.getJSONArray("credits"); + + boolean flag = true; + for (int i = 0; i < creditsRequired; i++) { + QuorumConsensusLogger.debug("Credit object: " + creditsArray.getJSONObject(i).toString()); + QuorumConsensusLogger.debug( + "Credit Hash: " + calculateHash(creditsArray.getJSONObject(i).toString(), "SHA3-256")); + String reHash = calculateHash(qstArray.getJSONObject(i).getString("credits"), "SHA3-256"); + if (!reHash.equals(qstArray.getJSONObject(i).getString("creditHash"))) { + QuorumConsensusLogger.debug("Recalculation " + reHash + " - " + + qstArray.getJSONObject(i).getString("creditHash")); + flag = false; + } + } + if (flag) { + + boolean verifySigns = true; + for (int i = 0; i < creditsRequired; i++) { + if (!Authenticate.verifySignature(creditsArray.getJSONObject(i).toString())) + verifySigns = false; + } + if (verifySigns) { + HashSet hashSet = new HashSet(); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < creditsArray.length(); i++) { + String sign = creditsArray.getJSONObject(i).getString("signature"); + String signHash = calculateHash(sign, "SHA3-256"); + hashSet.add(signHash); + } + long endTime = System.currentTimeMillis(); + QuorumConsensusLogger.debug("Total Time for HashSet: " + (endTime - startTime)); + if (hashSet.size() == qstArray.length() * 15) { + QuorumConsensusLogger.debug("Mining Verified"); + out.println("Verified"); + } else { + QuorumConsensusLogger + .debug("HashSet: " + hashSet.size() + " QST Size " + qstArray.length()); + QuorumConsensusLogger.debug("Mining Not Verified: Duplicates Found"); + out.println("440"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + } else { + out.println("441"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + } else { + out.println("442"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + // ! operation for quorum staking token ends here + } else + QuorumConsensusLogger.debug("Old Credits Mining / Whole RBT Token Transfer"); + String getRecData = null; try { getRecData = in.readLine(); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index f490d84e..f85cc7d0 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -434,7 +434,8 @@ public static void listenThread(JSONObject connectObject) { /** * This function check if the token is pinned by the given DID * - * @param token ID and DID of owner of the token to be checked + * @param tokenID + * @param DID of owner of the token to be checked * @return boolean value */ public static boolean checkTokenOwnershiByDID(String tokenID, String DID) { @@ -458,24 +459,27 @@ public static boolean checkTokenOwnershiByDID(String tokenID, String DID) { * This function generate Stake ID for a pleadged token. mined token can also be * found from stake ID * - * @param token ID to be staked + * @param stakedTokenID ID to be mined + * @param quorumDID ID to be mined + * @param minedTokenID ID to be mined * @return Stake ID for that token */ - public static String generateStakeID(String stakedTokenID) { - String stakeID = calculateHash("stake" + stakedTokenID, "SHA3-256"); - return stakeID; + public static String generateMineID(String stakedTokenID) { + String mineID = calculateHash("stake" + stakedTokenID, "SHA3-256"); + + return mineID; } /** * This function generate Stake ID for a pleadged token. mined token can also be * found from stake ID * - * @param token ID to be staked - * @return Stake ID for that token + * @return mine ID for that token */ - public static String minedTokenIDFromStakeID(String stakeID) { + public static String minedTokenIDFromMineID(String mineID) { + String KEY = "mined"; // ! multihash structure needed.. - String minedTokenID = calculateHash("stake" + stakeID, "SHA3-256"); + String minedTokenID = calculateHash("stake" + mineID, "SHA3-256"); return minedTokenID; } @@ -483,16 +487,82 @@ public static String minedTokenIDFromStakeID(String stakeID) { * This function generate Stake ID for a pleadged token. mined token can also be * found from stake ID * + * @return mine ID for that token + */ + public static String stakedQuorumDIDFromMineID(String mineID) { + String KEY = "staker"; + // ! multihash structure needed.. + String stakedQuorumDID = calculateHash("stake" + mineID, "SHA3-256"); + return stakedQuorumDID; + } + + /** + * This function generate Stake ID for a pleadged token. mined token can also be + * found from stake ID + * + * @return mine ID for that token + */ + public static String stakedTokenIDFromMineID(String mineID) { + String KEY = "staked"; + // ! multihash structure needed.. + String stakedTokenID = calculateHash("stake" + mineID, "SHA3-256"); + return stakedTokenID; + } + + public static int creditsRequiredForLevel() { + int creditsRequired = 0; + JSONObject resJsonData_credit = new JSONObject(); + String GET_URL_credit = SYNC_IP + "/getlevel"; + URL URLobj_credit; + try { + URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + FunctionsLogger.debug("response from service " + response_credit.toString()); + resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + creditsRequired = (int) Math.pow(2, (2 + level_credit)); + FunctionsLogger.debug("credits required " + creditsRequired); + + return creditsRequired; + + } else + FunctionsLogger.debug("GET request not OK"); + + } catch (Exception e) { + FunctionsLogger.debug("GET request not worked " + e.getMessage()); + } + return creditsRequired; + } + + /** + * This function calculates token height from tokenchain for the given token id + * (without considering ownership) + * found from stake ID + * * @param token ID to be staked * @return Stake ID for that token */ + public static int tokenHeightFromTokenID(String tokenID) { - int tokenChainLength = 32; + // height for current level x2 + int requiredHeight = 64; // ! get data from DID server or contact owner of mined token for token height - return tokenChainLength; + return requiredHeight; } /** @@ -502,20 +572,20 @@ public static int tokenHeightFromTokenID(String tokenID) { * @param token ID to be staked * @return boolean of exists or not */ - public static boolean checkStakeIDExists(String tokenID) { - boolean stakeIDExists = false; - String stakeID = calculateHash("stake" + tokenID, "SHA3-256"); - stakeIDExists = checkTokenOwnershiByDID(stakeID, stakeID); + public static boolean checkMineIDExists(String tokenID) { + boolean mineIDExists = false; + String mineID = calculateHash("stake" + tokenID, "SHA3-256"); + mineIDExists = checkTokenOwnershiByDID(mineID, mineID); try { ArrayList owners = dhtOwnerCheck(tokenID); if (!owners.isEmpty()) { - stakeIDExists = true; + mineIDExists = true; } } catch (InterruptedException | JSONException | IOException e) { - FunctionsLogger.error("JSONException Occurred while - checkStakeIDExists - check", e); + FunctionsLogger.error("JSONException Occurred while - checkMineIDExists - check", e); } - return stakeIDExists; + return mineIDExists; } /** @@ -963,8 +1033,8 @@ public static String checkDirectory() throws JSONException { File didImage = new File(DATA_PATH + myDID + "/DID.png"); File widImage = new File(DATA_PATH + myDID + "/PublicShare.png"); - File pvtImage = new File(DATA_PATH + myDID + "/PrivateShare.png"); - if (!didImage.exists() || !widImage.exists() || !pvtImage.exists()) { + // File pvtImage = new File(DATA_PATH + myDID + "/PrivateShare.png"); + if (!didImage.exists() || !widImage.exists()) { didImage.delete(); didImage.delete(); didImage.delete(); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 1e75a19e..37c4389c 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -260,19 +260,19 @@ public static String receive() { return APIResponse.toString(); } - // ! starts stakeID checks + // ! starts mineID checks for (int i = 0; i < wholeTokens.length(); ++i) { try { TokenReceiverLogger.debug("Checking stake ID for " + wholeTokens.getString(i) + " Please wait..."); - String stakeID = Functions.generateStakeID(tokenDetails); - stakeOwnersArray = IPFSNetwork.dhtOwnerCheck(stakeID); + String mineID = "mineID"; + stakeOwnersArray = IPFSNetwork.dhtOwnerCheck(mineID); if (stakeOwnersArray.size() > 1) { // ! check sign on pinned stake ID - String minedToken = Functions.minedTokenIDFromStakeID(stakeID); + String minedToken = Functions.minedTokenIDFromMineID(mineID); int minedTokenHeight = Functions.tokenHeightFromTokenID(minedToken); if (minedTokenHeight < 32) { @@ -298,7 +298,7 @@ public static String receive() { } } catch (IOException e) { - TokenReceiverLogger.trace("Ipfs dht find did not execute (stakeID check)"); + TokenReceiverLogger.trace("Ipfs dht find did not execute (mineID check)"); } } @@ -319,7 +319,7 @@ public static String receive() { return APIResponse.toString(); } - // ! ends stakeID checks + // ! ends mineID checks String senderToken = TokenDetails.toString(); String consensusID = calculateHash(senderToken, "SHA3-256"); From f9e90866922ee2fdb189c9cc7a6046e6cf0c5f8e Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 22 Feb 2022 12:02:55 +0530 Subject: [PATCH 004/179] transfer error code fix Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Resources/Functions.java | 34 ++++ .../rubix/TokenTransfer/TokenReceiver.java | 6 +- src/com/rubix/TokenTransfer/TokenSender.java | 175 +++++++++++------- 3 files changed, 147 insertions(+), 68 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index f85cc7d0..2354ae8f 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -455,6 +455,40 @@ public static boolean checkTokenOwnershiByDID(String tokenID, String DID) { return ownStatus; } + /** + * Move the selected token to bottom of the BNK00 file to avoid transaction + * failures. + * + * @param tokenID ID to be minedD to be mined + * @return null + */ + public static void demoteToken(String tokenID) { + + try { + String bankNew = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bankNewArray = new JSONArray(bankNew); + + JSONObject tokeJsonObject = new JSONObject(); + tokeJsonObject.put("tokenHash", tokenID); + + // remove tokenJsonObject from bankNewArray + for (int i = 0; i < bankNewArray.length(); i++) { + JSONObject temp = bankNewArray.getJSONObject(i); + if (temp.getString("tokenHash").equals(tokenID)) { + bankNewArray.remove(i); + break; + } + } + bankNewArray.put(tokeJsonObject); + + // write the new bankNewArray to file + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankNewArray.toString(), false); + + } catch (JSONException e) { + FunctionsLogger.error("JSONException Occurred", e); + } + } + /** * This function generate Stake ID for a pleadged token. mined token can also be * found from stake ID diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 37c4389c..d706ea2b 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -245,7 +245,7 @@ public static String receive() { owners.put(ownersArray.get(i).toString()); TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); TokenReceiverLogger.debug("Owners: " + owners); - output.println("200"); + output.println("420"); output.println(doubleSpentToken.toString()); output.println(owners.toString()); APIResponse.put("did", senderDidIpfsHash); @@ -304,7 +304,7 @@ public static String receive() { if (incompleteStake) { TokenReceiverLogger.debug("Token Height not reached for corresponding Staked Tokens " + stakedToken); - output.println("200"); + output.println("425"); output.println(stakedToken.toString()); output.println("stakes not complete"); APIResponse.put("did", senderDidIpfsHash); @@ -329,7 +329,7 @@ public static String receive() { if (!IPFSNetwork.dhtEmpty(consensusIDIPFSHash, ipfs)) { TokenReceiverLogger.debug("consensus ID not unique" + consensusIDIPFSHash); - output.println("200"); + output.println("421"); APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index efc01e02..4667c53c 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -1,18 +1,46 @@ package com.rubix.TokenTransfer; -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.apache.log4j.PropertyConfigurator; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import javax.net.ssl.HttpsURLConnection; -import java.io.*; +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.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.formatAmount; +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.partTokenBalance; +import static com.rubix.Resources.Functions.readFile; +import static com.rubix.Resources.Functions.removeToken; +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.pin; +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.SocketException; import java.net.URL; @@ -23,9 +51,20 @@ import java.util.Iterator; import java.util.List; -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.*; +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; +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 TokenSender { private static final Logger TokenSenderLogger = Logger.getLogger(TokenSender.class); @@ -93,8 +132,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } int intPart = (int) requestedAmount, wholeAmount; - TokenSenderLogger.debug("Requested Part: " +requestedAmount); - TokenSenderLogger.debug("Int Part: " +intPart); + TokenSenderLogger.debug("Requested Part: " + requestedAmount); + TokenSenderLogger.debug("Int Part: " + intPart); String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); JSONArray bankArray = new JSONArray(bankFile); JSONArray wholeTokens = new JSONArray(); @@ -107,10 +146,10 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception wholeTokens.put(bankArray.getJSONObject(i).getString("tokenHash")); } - for(int i = 0; i < wholeTokens.length(); i++){ + for (int i = 0; i < wholeTokens.length(); i++) { String tokenRemove = wholeTokens.getString(i); - for(int j = 0; j < bankArray.length(); j++){ - if(bankArray.getJSONObject(j).getString("tokenHash").equals(tokenRemove)) + for (int j = 0; j < bankArray.length(); j++) { + if (bankArray.getJSONObject(j).getString("tokenHash").equals(tokenRemove)) bankArray.remove(j); } } @@ -134,12 +173,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String tokenChainHash = add(TOKENCHAIN_PATH + wholeTokens.get(i) + ".json", ipfs); wholeTokenChainHash.put(tokenChainHash); - String tokenChainFileContent = readFile(TOKENCHAIN_PATH + wholeTokens.get(i) + ".json"); JSONArray tokenChainFileArray = new JSONArray(tokenChainFileContent); JSONArray previousSenderArray = new JSONArray(); for (int j = 0; j < tokenChainFileArray.length(); j++) { - String peerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", tokenChainFileArray.getJSONObject(j).getString("sender")); + String peerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", + tokenChainFileArray.getJSONObject(j).getString("sender")); previousSenderArray.put(peerID); } @@ -152,7 +191,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception Double decimalAmount = requestedAmount - wholeAmount; decimalAmount = formatAmount(decimalAmount); - TokenSenderLogger.debug("Decimal Part: " +decimalAmount); + TokenSenderLogger.debug("Decimal Part: " + decimalAmount); boolean newPart = false, oldNew = false; JSONObject amountLedger = new JSONObject(); @@ -175,8 +214,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception JSONArray selectParts = new JSONArray(partContentArray); while (counter > 0.000D) { counter = formatAmount(counter); - TokenSenderLogger.debug("Counter: " + formatAmount(counter) ); - if(!(selectParts.length() == 0)) { + TokenSenderLogger.debug("Counter: " + formatAmount(counter)); + if (!(selectParts.length() == 0)) { TokenSenderLogger.debug("Old Parts"); String currentPartToken = selectParts.getJSONObject(0).getString("tokenHash"); Double currentPartBalance = partTokenBalance(currentPartToken); @@ -189,7 +228,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception partTokens.put(currentPartToken); counter -= currentPartBalance; selectParts.remove(0); - }else{ + } else { oldNew = true; TokenSenderLogger.debug("Old Parts then new parts"); String chosenToken = bankArray.getJSONObject(0).getString("tokenHash"); @@ -200,13 +239,13 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception File chainFile = new File(TOKENCHAIN_PATH.concat(chosenToken).concat(".json")); chainFile.renameTo(new File(PART_TOKEN_CHAIN_PATH.concat(chosenToken).concat(".json"))); - File shiftedFile = new File(PAYMENTS_PATH.concat("ShiftedTokens.json")); if (!shiftedFile.exists()) { shiftedFile.createNewFile(); JSONArray shiftedTokensArray = new JSONArray(); shiftedTokensArray.put(chosenToken); - writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedTokensArray.toString(), false); + writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedTokensArray.toString(), + false); } else { String shiftedContent = readFile(PAYMENTS_PATH.concat("ShiftedTokens.json")); JSONArray shiftedArray = new JSONArray(shiftedContent); @@ -219,11 +258,10 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } String tokenChainPath = "", tokenPath = ""; - if(newPart) { + if (newPart) { tokenChainPath = TOKENCHAIN_PATH; tokenPath = TOKENS_PATH; - } - else{ + } else { tokenChainPath = TOKENCHAIN_PATH.concat("PARTS/"); tokenPath = TOKENS_PATH.concat("PARTS/"); } @@ -251,7 +289,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String hash = add(tokenPath + partTokens.getString(i), ipfs); pin(hash, ipfs); - String chainContent = readFile(tokenChainPath.concat(partTokens.getString(i)).concat(".json")); JSONArray chainArray = new JSONArray(); JSONArray finalChainArray = new JSONArray(chainContent); @@ -263,13 +300,17 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } else if (finalChainArray.length() > 1) { if (j == 0) { object.put("previousHash", ""); - object.put("nextHash", calculateHash(finalChainArray.getJSONObject(j + 1).getString("tid"), "SHA3-256")); + object.put("nextHash", + calculateHash(finalChainArray.getJSONObject(j + 1).getString("tid"), "SHA3-256")); } else if (j == finalChainArray.length() - 1) { - object.put("previousHash", calculateHash(finalChainArray.getJSONObject(j - 1).getString("tid"), "SHA3-256")); + object.put("previousHash", + calculateHash(finalChainArray.getJSONObject(j - 1).getString("tid"), "SHA3-256")); object.put("nextHash", ""); } else { - object.put("previousHash", calculateHash(finalChainArray.getJSONObject(j - 1).getString("tid"), "SHA3-256")); - object.put("nextHash", calculateHash(finalChainArray.getJSONObject(j + 1).getString("tid"), "SHA3-256")); + object.put("previousHash", + calculateHash(finalChainArray.getJSONObject(j - 1).getString("tid"), "SHA3-256")); + object.put("nextHash", + calculateHash(finalChainArray.getJSONObject(j + 1).getString("tid"), "SHA3-256")); } } chainArray.put(object); @@ -280,13 +321,15 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception partTokenChainHash.put(add(tokenChainPath.concat(partTokens.getString(i)).concat(".json"), ipfs)); } - String authSenderByRecHash = calculateHash(wholeTokens.toString() + wholeTokenChainHash.toString() + partTokens.toString() + partTokenChainHash.toString() + receiverDidIpfsHash + senderDidIpfsHash + comment, "SHA3-256"); + String authSenderByRecHash = calculateHash( + wholeTokens.toString() + wholeTokenChainHash.toString() + partTokens.toString() + + partTokenChainHash.toString() + receiverDidIpfsHash + senderDidIpfsHash + comment, + "SHA3-256"); TokenSenderLogger.debug("Hash to verify Sender: " + authSenderByRecHash); String tid = calculateHash(authSenderByRecHash, "SHA3-256"); TokenSenderLogger.debug("Sender by Receiver Hash " + authSenderByRecHash); TokenSenderLogger.debug("TID on sender " + tid); - JSONArray quorumArray; JSONArray alphaQuorum = new JSONArray(); JSONArray betaQuorum = new JSONArray(); @@ -308,7 +351,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); deleteFile(LOGGER_PATH + "tempgamma"); - quorumArray = getQuorum(betaHash, gammaHash, senderDidIpfsHash, receiverDidIpfsHash, wholeTokens.length()); + quorumArray = getQuorum(betaHash, gammaHash, senderDidIpfsHash, receiverDidIpfsHash, + wholeTokens.length()); break; } @@ -372,7 +416,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } - syncDataTable(receiverDidIpfsHash, null); receiverPeerId = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", receiverDidIpfsHash); @@ -390,7 +433,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } - String receiverWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", receiverDidIpfsHash); + String receiverWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", + receiverDidIpfsHash); if (!receiverWidIpfsHash.equals("")) { nodeData(receiverDidIpfsHash, receiverWidIpfsHash, ipfs); } else { @@ -439,7 +483,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } - if (peerAuth != null && (!peerAuth.equals("200"))) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); TokenSenderLogger.info("Sender Data Not Available"); @@ -472,7 +515,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } else { JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); - newLastObject.put("previousHash", calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + newLastObject.put("previousHash", + calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); } Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); @@ -505,15 +549,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception IPFSNetwork.addHashOnly(LOGGER_PATH + "doubleSpend", ipfs); deleteFile(LOGGER_PATH + "doubleSpend"); - JSONObject tokenObject = new JSONObject(); tokenObject.put("tokenDetails", tokenDetails); tokenObject.put("previousSender", tokenPreviousSender); tokenObject.put("amount", requestedAmount); tokenObject.put("amountLedger", amountLedger); - - /** * Sending Token Details to Receiver * Receiver to authenticate Tokens (Double Spending, IPFS availability) @@ -568,6 +609,10 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception TokenSenderLogger.info("Token wholly spent already"); APIResponse.put("message", "Token wholly spent already"); break; + case "425": + TokenSenderLogger.info("Stake incomplete for a selected token"); + APIResponse.put("message", "Stake incomplete for a selected token"); + break; } executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); @@ -595,9 +640,9 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception dataObject.put("betaList", betaPeersList); dataObject.put("gammaList", gammaPeersList); - InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 100, alphaSize, ""); - TokenSenderLogger.debug("length on sender " + InitiatorConsensus.quorumSignature.length() + "response count " + InitiatorConsensus.quorumResponse); + TokenSenderLogger.debug("length on sender " + InitiatorConsensus.quorumSignature.length() + "response count " + + InitiatorConsensus.quorumResponse); if (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { TokenSenderLogger.debug("Consensus Failed"); senderDetails2Receiver.put("status", "Consensus Failed"); @@ -664,7 +709,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception unpin(String.valueOf(wholeTokens.get(i)), ipfs); repo(ipfs); - TokenSenderLogger.debug("Unpinned Tokens"); output.println("Unpinned"); String confirmation; @@ -719,7 +763,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); - APIResponse.put("message", "Receiver " + receiverDidIpfsHash + "is unable to respond! - Share Confirmation"); + APIResponse.put("message", + "Receiver " + receiverDidIpfsHash + "is unable to respond! - Share Confirmation"); return APIResponse; } @@ -756,11 +801,10 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception updateQuorum(quorumArray, signedQuorumList, true, type); - JSONArray allTokens = new JSONArray(); - for(int i = 0; i < wholeTokens.length(); i++) + for (int i = 0; i < wholeTokens.length(); i++) allTokens.put(wholeTokens.getString(i)); - for(int i = 0; i < partTokens.length(); i++) + for (int i = 0; i < partTokens.length(); i++) allTokens.put(partTokens.getString(i)); TokenSenderLogger.debug("4"); @@ -782,7 +826,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception requestedAmount = formatAmount(requestedAmount); transactionRecord.put("amount-spent", requestedAmount); - JSONArray transactionHistoryEntry = new JSONArray(); transactionHistoryEntry.put(transactionRecord); @@ -818,7 +861,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } else { JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); - newLastObject.put("previousHash", calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + newLastObject.put("previousHash", + calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); } Double amount = formatAmount(decimalAmount); @@ -839,7 +883,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception File chainFile = new File(TOKENCHAIN_PATH.concat(partTokens.getString(0)).concat(".json")); chainFile.renameTo(new File(PART_TOKEN_CHAIN_PATH.concat(partTokens.getString(0)).concat(".json"))); - File shiftedFile = new File(PAYMENTS_PATH.concat("ShiftedTokens.json")); if (!shiftedFile.exists()) { shiftedFile.createNewFile(); @@ -865,10 +908,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } else { JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); - newLastObject.put("previousHash", calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + newLastObject.put("previousHash", calculateHash( + chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); } - TokenSenderLogger.debug("Amount from ledger: " + formatAmount(amountLedger.getDouble(partTokens.getString(i)))); + TokenSenderLogger + .debug("Amount from ledger: " + formatAmount(amountLedger.getDouble(partTokens.getString(i)))); Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); newLastObject.put("senderSign", senderSign); @@ -880,7 +925,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception newLastObject.put("role", "Sender"); newLastObject.put("amount", amount); chainArray.put(newLastObject); - writeToFile(TOKENCHAIN_PATH.concat("PARTS/").concat(partTokens.getString(i)).concat(".json"), chainArray.toString(), false); + writeToFile(TOKENCHAIN_PATH.concat("PARTS/").concat(partTokens.getString(i)).concat(".json"), + chainArray.toString(), false); TokenSenderLogger.debug("Checking Parts Token Balance ..."); Double availableParts = partTokenBalance(partTokens.getString(i)); @@ -897,12 +943,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception deleteFile(PART_TOKEN_PATH.concat(partTokens.getString(i))); } } - if(oldNew){ - String token = partTokens.getString(partTokens.length()-1); + if (oldNew) { + String token = partTokens.getString(partTokens.length() - 1); String bnk = readFile(PAYMENTS_PATH.concat("BNK00.json")); JSONArray bnkArray = new JSONArray(bnk); - for(int i = 0; i < bnkArray.length(); i++){ - if(bnkArray.getJSONObject(i).getString("tokenHash").equals(token)) + for (int i = 0; i < bnkArray.length(); i++) { + if (bnkArray.getJSONObject(i).getString("tokenHash").equals(token)) bnkArray.remove(i); } writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bnkArray.toString(), false); @@ -915,7 +961,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } - //Populating data to explorer + // Populating data to explorer if (!EXPLORER_IP.contains("127.0.0.1")) { List tokenList = new ArrayList<>(); @@ -971,7 +1017,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception TokenSenderLogger.debug(response.toString()); } - TokenSenderLogger.info("Transaction Successful"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); output.close(); From 14882c41033e587ca219e70e7f3ec47bc8bc973e Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 22 Feb 2022 16:33:14 +0530 Subject: [PATCH 005/179] comments for RBT receiver check Signed-off-by: Nidhin Mahesh A --- .../rubix/AuthenticateNode/Authenticate.java | 28 +------------------ .../rubix/TokenTransfer/TokenReceiver.java | 15 ++++++++-- 2 files changed, 13 insertions(+), 30 deletions(-) diff --git a/src/com/rubix/AuthenticateNode/Authenticate.java b/src/com/rubix/AuthenticateNode/Authenticate.java index 5218b56c..866cc40b 100644 --- a/src/com/rubix/AuthenticateNode/Authenticate.java +++ b/src/com/rubix/AuthenticateNode/Authenticate.java @@ -42,38 +42,12 @@ 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); JSONObject details = new JSONObject(detailString); String decentralizedID = details.getString("did"); String hash = details.getString("hash"); - - String quorumSign; - String tokenSign; - String TIDSign; - JSONObject signs = new JSONObject(); - - if (details.optJSONObject(quorumSign) != null) { - - JSONObject signatureObject = details.getJSONObject("signatures"); - quorumSign = signatureObject.getString("QuorumSign"); - tokenSign = signatureObject.getString("TokenSign"); - TIDSign = signatureObject.getString("TIDSign"); - - signs.put(tokenSign, false); - signs.put(quorumSign, false); - signs.put(TIDSign, false); - - } else { - // make all three params in JSONObject signs as true - signs.put(quorumSign, false); - signs.put(tokenSign, true); - signs.put(TIDSign, true); - - quorumSign = details.getString("signature"); - } - + String signature = details.getString("signature"); syncDataTable(decentralizedID, null); String walletIdIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", decentralizedID); nodeData(decentralizedID, walletIdIpfsHash, ipfs); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index d706ea2b..ac1a1a31 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -205,6 +205,7 @@ public static String receive() { JSONArray doubleSpentToken = new JSONArray(); JSONArray stakedToken = new JSONArray(); boolean tokenOwners = true; + boolean validTxnSignatures = true; boolean incompleteStake = false; ArrayList ownersArray = new ArrayList(); ArrayList stakeOwnersArray = new ArrayList(); @@ -212,7 +213,8 @@ public static String receive() { JSONArray ownersReceived = new JSONArray(); for (int i = 0; i < wholeTokens.length(); ++i) { try { - TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + " Please wait..."); + TokenReceiverLogger.debug("Checking owners and credits / signatures for " + wholeTokens.getString(i) + + " Please wait..."); ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); if (ownersArray.size() > 2) { @@ -233,13 +235,20 @@ public static String receive() { tokenOwners = false; } } + + // ! to avoid fraud multiple pinning of tokens (fork) + // ! check sender has signatures and credits to back the token transfer even if + // ! someone has pinned the token + // ! check if sender has provided credits to quorum for this transfer + // validTxnSignatures = false; + } catch (IOException e) { TokenReceiverLogger.trace("Ipfs dht find did not execute (double spend check)"); } } - if (!tokenOwners) { + if (!tokenOwners && !validTxnSignatures) { JSONArray owners = new JSONArray(); for (int i = 0; i < ownersArray.size(); i++) owners.put(ownersArray.get(i).toString()); @@ -260,7 +269,7 @@ public static String receive() { return APIResponse.toString(); } - // ! starts mineID checks + // ! starts mine ID check for (int i = 0; i < wholeTokens.length(); ++i) { try { From fa2a5cb575aeeb3c3c5967541e52fffcee07243e Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 24 Feb 2022 11:36:09 +0530 Subject: [PATCH 006/179] staking communications Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 75 ++++++----- src/com/rubix/Consensus/QuorumConsensus.java | 123 ++++++------------ .../rubix/TokenTransfer/TokenReceiver.java | 45 ++++--- src/com/rubix/TokenTransfer/TokenSender.java | 2 +- 4 files changed, 109 insertions(+), 136 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 9c94db13..46e7392f 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -7,6 +7,7 @@ import static com.rubix.Resources.Functions.checkTokenOwnershiByDID; import static com.rubix.Resources.Functions.creditsRequiredForLevel; import static com.rubix.Resources.Functions.deleteFile; +import static com.rubix.Resources.Functions.generateMineID; import static com.rubix.Resources.Functions.getValues; import static com.rubix.Resources.Functions.minQuorum; import static com.rubix.Resources.Functions.nodeData; @@ -284,7 +285,7 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri InitiatorConsensusLogger.debug("Credit Verification failed: Credits hash mismatch"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } else if (qResponse[j].equals("443")) { - InitiatorConsensusLogger.debug("Failed to initialize credit verification"); + InitiatorConsensusLogger.debug("Failed to Initialize Credit Verification"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } } @@ -364,16 +365,15 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (operation.equals("new-credits-mining")) { Thread[] stakingThreads = new Thread[signedAlphaQuorumID.length]; - // ? one of the validators stake 1 RBT and send the stake ID to the miner. - // choose a quorum member from 1 to 5 who have signed the transaction + + // choosing a quorum member from 1 to 5 who have signed the transaction for (int p = 0; p < signedAlphaQuorumID.length; p++) { int s = p; stakingThreads[p] = new Thread(() -> { try { InitiatorConsensusLogger.debug( "Contacting Signed Alpha Quorum ID : " + signedAlphaQuorumID[s] - + " for staking. Index " - + s); + + " for staking. Index: " + s); qSocket[s] = new Socket("127.0.0.1", PORT + s); qSocket[s].setSoTimeout(socketTimeOut); @@ -387,19 +387,20 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri // convert to JSON array JSONArray stakingTokenDetals = new JSONArray(qResponse[s]); // get token chain and token ID from the array - String tokenID = stakingTokenDetals.getString(0); - JSONArray tokenChain = stakingTokenDetals.getJSONArray(1); + String stakingTokenHash = stakingTokenDetals.getString(0); + JSONArray stakingTokenChain = stakingTokenDetals.getJSONArray(1); String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", signedAlphaQuorumID[s]); - if (checkTokenOwnershiByDID(tokenID, stakingQuorumDID) - && tokenChain.length() > creditsRequiredForLevel()) { + if (checkTokenOwnershiByDID(stakingTokenHash, stakingQuorumDID) + && stakingTokenChain.length() > creditsRequiredForLevel()) { InitiatorConsensusLogger.debug("Staking Token Received and Verified from " + signedAlphaQuorumID[s] + " " + qResponse[s]); - String mineID = "1234caf17ff4d84f8614091bf222c03ed43d0bd5f2ee75c1814372c62xxxxx"; - InitiatorConsensusLogger.debug("Sending mine ID to miner " + mineID); + String mineID = generateMineID(stakingTokenHash); + InitiatorConsensusLogger + .debug("Sending mine ID to miner :" + mineID); qOut[s].println(mineID); try { @@ -419,36 +420,42 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (Authenticate.verifySignature(detailsToVerify.toString())) { - FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mineID.txt"), - true); - shareWriter.write(qResponse[s]); - shareWriter.close(); - File readMineID = new File(LOGGER_PATH + "mineID.txt"); - String mineData = add(readMineID.toString(), ipfs); - pin(mineData, ipfs); + if (anyoneStaked == 0) { + FileWriter shareWriter = new FileWriter( + new File(LOGGER_PATH + "mineID.txt"), + true); + shareWriter.write(qResponse[s]); + shareWriter.close(); + File readMineID = new File(LOGGER_PATH + "mineID.txt"); + String mineData = add(readMineID.toString(), ipfs); + pin(mineData, ipfs); - File mineIDFile = new File( - WALLET_DATA_PATH.concat("/Stakes/").concat(mineData).concat(".json")); - if (!mineIDFile.exists()) - mineIDFile.createNewFile(); - writeToFile(mineIDFile.toString(), qResponse[s], false); + File mineIDFile = new File( + WALLET_DATA_PATH.concat("/Stakes/").concat(mineData) + .concat(".json")); + if (!mineIDFile.exists()) + mineIDFile.createNewFile(); + writeToFile(mineIDFile.toString(), qResponse[s], false); - InitiatorConsensusLogger.debug("Mine object: " + mineData); - deleteFile(LOGGER_PATH + "mineID.txt"); + InitiatorConsensusLogger.debug("Mine object: " + mineData); + deleteFile(LOGGER_PATH + "mineID.txt"); - InitiatorConsensusLogger.debug("Staking Successful at index " + s); + InitiatorConsensusLogger.debug("Staking Successful at index " + s); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); - JSONObject stakingInfo = new JSONObject(); - stakingInfo.put("StakerDID", stakingQuorumDID); - stakingInfo.put("StakedokenID", tokenID); - stakingInfo.put("minedToken", detailsToken); + JSONObject stakingInfo = new JSONObject(); + stakingInfo.put("StakerDID", stakingQuorumDID); + stakingInfo.put("StakedokenID", stakingTokenHash); + stakingInfo.put("minedToken", detailsToken); - JSONArray creditArray = new JSONArray(); - creditArray.put(finalQuorumSignsArray); + JSONArray creditArray = new JSONArray(); + creditArray.put(finalQuorumSignsArray); - qOut[s].println(creditArray); + qOut[s].println(creditArray); + } else { + qOut[s].println("null"); + } } else { diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 6565012e..69a863e1 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -3,7 +3,10 @@ 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.PAYMENTS_PATH; 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; @@ -12,6 +15,7 @@ import static com.rubix.Resources.Functions.getValues; import static com.rubix.Resources.Functions.initHash; 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; @@ -214,99 +218,58 @@ public void run() { if (operation.equals("stake-token")) { - QuorumConsensusLogger.debug("Staking Credits"); - String getNewCreditsData = null; - String tokenToStake = null; + QuorumConsensusLogger.debug("Initiating Token Staking for Newly Mined Token..."); + String mineID = null; + JSONArray tokenToStake = new JSONArray(); + + String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bankArray = new JSONArray(bankFile); + + // pick last object from bank array + JSONObject bankObject = bankArray.getJSONObject(0); + String tokenHash = bankObject.getString("tokenHash"); + tokenToStake.put(tokenHash); + + File tokenFile = new File(TOKENS_PATH + tokenHash); + File tokenchainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); + + if (tokenFile.exists() && tokenchainFile.exists()) { + + String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); + tokenToStake.put(tokenChain); + + out.println(tokenToStake); + } else { + QuorumConsensusLogger.debug("Token Staking Failed: Token files missing"); + out.println("443"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + // move that token ID to bottom of BNK00 file try { - getNewCreditsData = in.readLine(); + mineID = in.readLine(); } catch (SocketException e) { QuorumConsensusLogger.debug("Sender Input Stream Null - Stake ID details"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - // Verify QST Credits - JSONObject qstObject = new JSONObject(getNewCreditsData); - - // Get level of token from advisory node - int creditsRequired = 0; - JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getlevel"; - URL URLobj_credit = new URL(GET_URL_credit); - HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); - con_credit.setRequestMethod("GET"); - int responseCode_credit = con_credit.getResponseCode(); - System.out.println("GET Response Code :: " + responseCode_credit); - if (responseCode_credit == HttpURLConnection.HTTP_OK) { - BufferedReader in_credit = new BufferedReader( - new InputStreamReader(con_credit.getInputStream())); - String inputLine_credit; - StringBuffer response_credit = new StringBuffer(); - while ((inputLine_credit = in_credit.readLine()) != null) { - response_credit.append(inputLine_credit); - } - in_credit.close(); - QuorumConsensusLogger.debug("response from service " + response_credit.toString()); - resJsonData_credit = new JSONObject(response_credit.toString()); - int level_credit = resJsonData_credit.getInt("level"); - creditsRequired = (int) Math.pow(2, (2 + level_credit)); - QuorumConsensusLogger.debug("credits required " + creditsRequired); - } else - QuorumConsensusLogger.debug("Advisory GET request not worked"); - - // Level 1 Verification: Verify hash of n objects - JSONArray qstArray = qstObject.getJSONArray("qstArray"); - JSONArray creditsArray = qstObject.getJSONArray("credits"); + if (mineID != null) { + QuorumConsensusLogger.debug("Stake ID: " + mineID); + String mineIDSigned = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + mineID); + out.println(mineIDSigned); + } else { + QuorumConsensusLogger.debug("Stake ID: Null"); + } boolean flag = true; - for (int i = 0; i < creditsRequired; i++) { - QuorumConsensusLogger.debug("Credit object: " + creditsArray.getJSONObject(i).toString()); - QuorumConsensusLogger.debug( - "Credit Hash: " + calculateHash(creditsArray.getJSONObject(i).toString(), "SHA3-256")); - String reHash = calculateHash(qstArray.getJSONObject(i).getString("credits"), "SHA3-256"); - if (!reHash.equals(qstArray.getJSONObject(i).getString("creditHash"))) { - QuorumConsensusLogger.debug("Recalculation " + reHash + " - " - + qstArray.getJSONObject(i).getString("creditHash")); - flag = false; - } - } + if (flag) { - boolean verifySigns = true; - for (int i = 0; i < creditsRequired; i++) { - if (!Authenticate.verifySignature(creditsArray.getJSONObject(i).toString())) - verifySigns = false; - } - if (verifySigns) { - HashSet hashSet = new HashSet(); - long startTime = System.currentTimeMillis(); - for (int i = 0; i < creditsArray.length(); i++) { - String sign = creditsArray.getJSONObject(i).getString("signature"); - String signHash = calculateHash(sign, "SHA3-256"); - hashSet.add(signHash); - } - long endTime = System.currentTimeMillis(); - QuorumConsensusLogger.debug("Total Time for HashSet: " + (endTime - startTime)); - if (hashSet.size() == qstArray.length() * 15) { - QuorumConsensusLogger.debug("Mining Verified"); - out.println("Verified"); - } else { - QuorumConsensusLogger - .debug("HashSet: " + hashSet.size() + " QST Size " + qstArray.length()); - QuorumConsensusLogger.debug("Mining Not Verified: Duplicates Found"); - out.println("440"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - } else { - out.println("441"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } } else { out.println("442"); socket.close(); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index ac1a1a31..4578fdf8 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -248,38 +248,41 @@ public static String receive() { } } - if (!tokenOwners && !validTxnSignatures) { - JSONArray owners = new JSONArray(); - for (int i = 0; i < ownersArray.size(); i++) - owners.put(ownersArray.get(i).toString()); - TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); - TokenReceiverLogger.debug("Owners: " + owners); - output.println("420"); - output.println(doubleSpentToken.toString()); - output.println(owners.toString()); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + owners); - IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); + if (!tokenOwners) { + // JSONArray owners = new JSONArray(); + // for (int i = 0; i < ownersArray.size(); i++) + // owners.put(ownersArray.get(i).toString()); + // TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); + // TokenReceiverLogger.debug("Owners: " + owners); + // output.println("420"); + // output.println(doubleSpentToken.toString()); + // output.println(owners.toString()); + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", "null"); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + + // owners); + // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + // output.close(); + // input.close(); + // sk.close(); + // ss.close(); + // return APIResponse.toString(); + + TokenReceiverLogger.debug("Multiple Pins for " + doubleSpentToken); } // ! starts mine ID check for (int i = 0; i < wholeTokens.length(); ++i) { try { - TokenReceiverLogger.debug("Checking stake ID for " + wholeTokens.getString(i) + " Please wait..."); + TokenReceiverLogger.debug("Checking mine ID for " + wholeTokens.getString(i) + " Please wait..."); String mineID = "mineID"; stakeOwnersArray = IPFSNetwork.dhtOwnerCheck(mineID); if (stakeOwnersArray.size() > 1) { - // ! check sign on pinned stake ID + // ! check sign on pinned mine ID String minedToken = Functions.minedTokenIDFromMineID(mineID); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 4667c53c..75cf0d49 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -545,7 +545,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String doubleSpend = calculateHash(doubleSpendString, "SHA3-256"); writeToFile(LOGGER_PATH + "doubleSpend", doubleSpend, false); - TokenSenderLogger.debug("********Double Spend Hash*********: " + doubleSpend); + TokenSenderLogger.debug("********Double Spend Hash********* : " + doubleSpend); IPFSNetwork.addHashOnly(LOGGER_PATH + "doubleSpend", ipfs); deleteFile(LOGGER_PATH + "doubleSpend"); From 4aa63960838c4ed0326543b60caf6af9edbce3b1 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 24 Feb 2022 16:07:43 +0530 Subject: [PATCH 007/179] staking lock Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 37 +++++++++++++------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 46e7392f..eee784ad 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -46,9 +46,11 @@ public class InitiatorConsensus { public static volatile JSONObject quorumSignature = new JSONObject(); private static final Object countLock = new Object(); + private static final Object stakeLock = 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 boolean stakeComplete = false; public static volatile JSONArray finalQuorumSignsArray = new JSONArray(); /** @@ -80,19 +82,20 @@ private static synchronized boolean voteNCount(int i, int quorumSize) { /** * This method increments the quorumResponse variable */ - // private static synchronized boolean selectStakingQuorum(String DID) { + // private static synchronized boolean stakingQuorumExists(int i) { // boolean status; // PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - // synchronized (countLock) { - // if (quorumResponse[i] < minQuorum(quorumSize)) { + // synchronized (stakeLock) { + // if (signedAlphaQuorumID[i] < 1) { // quorumResponse[i]++; - // InitiatorConsensusLogger.debug("quorum response added index " + i + " is " + + // InitiatorConsensusLogger + // .debug("quorum response for staking added index " + i + " is " + // quorumResponse[i] - // + " quorumsize " + minQuorum(quorumSize)); - // status = true; - // } else { + // + " quorumsize "); // status = false; - // InitiatorConsensusLogger.debug("Staking Reached"); + // } else { + // status = true; + // InitiatorConsensusLogger.debug("Staking Reached for index " + i); // } // } // return status; @@ -420,11 +423,11 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (Authenticate.verifySignature(detailsToVerify.toString())) { - if (anyoneStaked == 0) { + if (!stakeComplete) { FileWriter shareWriter = new FileWriter( new File(LOGGER_PATH + "mineID.txt"), true); - shareWriter.write(qResponse[s]); + shareWriter.write(detailsToVerify.toString(0)); shareWriter.close(); File readMineID = new File(LOGGER_PATH + "mineID.txt"); String mineData = add(readMineID.toString(), ipfs); @@ -450,16 +453,26 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri stakingInfo.put("minedToken", detailsToken); JSONArray creditArray = new JSONArray(); - creditArray.put(finalQuorumSignsArray); + + for (int i = 0; i < creditsRequiredForLevel(); i++) { + + creditArray.put(finalQuorumSignsArray); + } qOut[s].println(creditArray); + + stakeComplete = true; } else { + + InitiatorConsensusLogger.debug("sending null for slow quorum"); qOut[s].println("null"); + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); } } else { - InitiatorConsensusLogger.debug("sending null for slow quorum "); + InitiatorConsensusLogger.debug("sending null for slow quorum"); qOut[s].println("null"); IPFSNetwork.executeIPFSCommands( "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); From 99b10508be5085f82394548283ca7d83ce9fbf2b Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 25 Feb 2022 11:43:48 +0530 Subject: [PATCH 008/179] 15 quorum signatures and staking signatures to tokenchain Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/InitiatorConsensus.java | 10 ++++++++++ src/com/rubix/Mining/ProofCredits.java | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index eee784ad..51401347 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -45,6 +45,7 @@ public class InitiatorConsensus { public static Logger InitiatorConsensusLogger = Logger.getLogger(InitiatorConsensus.class); public static volatile JSONObject quorumSignature = new JSONObject(); + public static volatile JSONObject stakingSignature = new JSONObject(); private static final Object countLock = new Object(); private static final Object stakeLock = new Object(); private static final Object signLock = new Object(); @@ -423,6 +424,15 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (Authenticate.verifySignature(detailsToVerify.toString())) { + stakingSignature.put("miningTransaction", mineID); + stakingSignature.put("mineID", mineID); + stakingSignature.put("stakingQuorumDID", mineID); + stakingSignature.put("stakingToken", mineID); + stakingSignature.put("stakingTokenSignature", mineID); + stakingSignature.put("TIDSignature", mineID); + stakingSignature.put("miningTokenSignature", qResponse[s]); + stakingSignature.put("mineIDSignature", mineID); + if (!stakeComplete) { FileWriter shareWriter = new FileWriter( new File(LOGGER_PATH + "mineID.txt"), diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index e4ce6292..1e1d9ec3 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -345,6 +345,12 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); deleteFile(LOGGER_PATH + "tempToken"); writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", "[]", false); + // genesis signatures + updateJSON("add", TOKENCHAIN_PATH + tokenHash + ".json", + InitiatorConsensus.quorumSignature.toString()); + // staking signatures + updateJSON("add", TOKENCHAIN_PATH + tokenHash + ".json", + InitiatorConsensus.stakingSignature.toString()); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); JSONArray tempArray = new JSONArray(); From 26b77285d128f7f050262978359c2b2a391e09c6 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 25 Feb 2022 16:02:37 +0530 Subject: [PATCH 009/179] current owner check Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 4578fdf8..44c87d88 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -670,6 +670,12 @@ public static String receive() { groupTokens.add(wholeTokens.getString(k)); } + // ! calculating owner hash for each token + + String privatePicker = calculateHash(wholeTokens.getString(i).concat(receiverDidIpfsHash), + "SHA3-256"); + // String privatePoistions = + JSONArray arrToken = new JSONArray(); JSONObject objectToken = new JSONObject(); objectToken.put("tokenHash", wholeTokens.getString(i)); @@ -681,6 +687,8 @@ public static String receive() { obj2.put("group", groupTokens); obj2.put("comment", comment); obj2.put("tid", tid); + // ! add current owner hash here.. + // obj2.put("currentOwner", senderDidIpfsHash); arr1.put(obj2); writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); } From b44a8d801d333bd4c97449ad4109f32bac58d031 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 2 Mar 2022 17:52:00 +0530 Subject: [PATCH 010/179] Fix signature exchange during staking Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 52 ++++++++++++----- src/com/rubix/Consensus/QuorumConsensus.java | 38 ++++++++++--- .../rubix/Constants/ConsensusConstants.java | 3 +- src/com/rubix/Constants/MiningConstants.java | 14 +++++ src/com/rubix/Resources/Functions.java | 56 +------------------ src/com/rubix/Resources/IPFSNetwork.java | 12 ++++ .../rubix/TokenTransfer/TokenReceiver.java | 47 +++++++++------- 7 files changed, 122 insertions(+), 100 deletions(-) create mode 100644 src/com/rubix/Constants/MiningConstants.java diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 51401347..f0286973 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -1,20 +1,29 @@ package com.rubix.Consensus; +import static com.rubix.Constants.MiningConstants.MINED_RBT; +import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; +import static com.rubix.Constants.MiningConstants.MINE_ID; +import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; +import static com.rubix.Constants.MiningConstants.MINING_TID; +import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; +import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; +import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; +import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; 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.WALLET_DATA_PATH; import static com.rubix.Resources.Functions.checkTokenOwnershiByDID; -import static com.rubix.Resources.Functions.creditsRequiredForLevel; import static com.rubix.Resources.Functions.deleteFile; -import static com.rubix.Resources.Functions.generateMineID; import static com.rubix.Resources.Functions.getValues; +import static com.rubix.Resources.Functions.levelHeight; import static com.rubix.Resources.Functions.minQuorum; import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.Functions.syncDataTable; import static com.rubix.Resources.Functions.writeToFile; import static com.rubix.Resources.IPFSNetwork.add; import static com.rubix.Resources.IPFSNetwork.forward; +import static com.rubix.Resources.IPFSNetwork.getMineID; import static com.rubix.Resources.IPFSNetwork.pin; import static com.rubix.Resources.IPFSNetwork.repo; import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; @@ -397,18 +406,26 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", signedAlphaQuorumID[s]); if (checkTokenOwnershiByDID(stakingTokenHash, stakingQuorumDID) - && stakingTokenChain.length() > creditsRequiredForLevel()) { + && stakingTokenChain.length() > levelHeight()) { InitiatorConsensusLogger.debug("Staking Token Received and Verified from " + signedAlphaQuorumID[s] + " " + qResponse[s]); - String mineID = generateMineID(stakingTokenHash); + String mineID = getMineID(stakingTokenHash, ipfs); InitiatorConsensusLogger .debug("Sending mine ID to miner :" + mineID); - qOut[s].println(mineID); + JSONObject detToSign = new JSONObject(); + detToSign.put(MINE_ID, stakingTokenHash); + detToSign.put(MINING_TID, stakingQuorumDID); + detToSign.put(MINED_RBT, stakingTokenHash); + qOut[s].println(detToSign.toString()); + + JSONObject stakingQuorumSigned = new JSONObject(); try { qResponse[s] = qIn[s].readLine(); + // convert to JSON array + stakingQuorumSigned = new JSONObject(qResponse[s]); InitiatorConsensusLogger.debug("Signature for Mining ID Received from " + signedAlphaQuorumID[s] + " " + qResponse[s]); } catch (SocketException e) { @@ -420,18 +437,23 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri JSONObject detailsToVerify = new JSONObject(); detailsToVerify.put("did", stakingQuorumDID); detailsToVerify.put("hash", mineID); - detailsToVerify.put("signature", qResponse[s]); + detailsToVerify.put("signature", stakingQuorumSigned.getString(MINE_ID_SIGN)); if (Authenticate.verifySignature(detailsToVerify.toString())) { - stakingSignature.put("miningTransaction", mineID); - stakingSignature.put("mineID", mineID); - stakingSignature.put("stakingQuorumDID", mineID); - stakingSignature.put("stakingToken", mineID); - stakingSignature.put("stakingTokenSignature", mineID); - stakingSignature.put("TIDSignature", mineID); - stakingSignature.put("miningTokenSignature", qResponse[s]); - stakingSignature.put("mineIDSignature", mineID); + stakingSignature.put(MINING_TID, detailsToken.getString("Tid")); + stakingSignature.put(MINED_RBT, detailsToken.getString("token")); + stakingSignature.put(MINE_ID, mineID); + stakingSignature.put(STAKED_QUORUM_DID, stakingQuorumDID); + stakingSignature.put(STAKED_TOKEN, stakingTokenHash); + + stakingSignature.put(STAKED_TOKEN_SIGN, stakingQuorumSigned.getString( + STAKED_TOKEN_SIGN)); + stakingSignature.put(MINING_TID_SIGN, stakingQuorumSigned.getString( + MINING_TID_SIGN)); + stakingSignature.put(MINED_RBT_SIGN, stakingQuorumSigned.getString( + MINED_RBT_SIGN)); + stakingSignature.put(MINE_ID_SIGN, stakingQuorumSigned.getString(MINE_ID_SIGN)); if (!stakeComplete) { FileWriter shareWriter = new FileWriter( @@ -464,7 +486,7 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri JSONArray creditArray = new JSONArray(); - for (int i = 0; i < creditsRequiredForLevel(); i++) { + for (int i = 0; i < levelHeight(); i++) { creditArray.put(finalQuorumSignsArray); } diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 69a863e1..e7b62572 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,5 +1,12 @@ package com.rubix.Consensus; +import static com.rubix.Constants.MiningConstants.MINED_RBT; +import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; +import static com.rubix.Constants.MiningConstants.MINE_ID; +import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; +import static com.rubix.Constants.MiningConstants.MINING_TID; +import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; +import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; @@ -240,7 +247,7 @@ public void run() { out.println(tokenToStake); } else { - QuorumConsensusLogger.debug("Token Staking Failed: Token files missing"); + QuorumConsensusLogger.debug("Token Staking Failed: Details of Picked Token is Missing"); out.println("443"); socket.close(); serverSocket.close(); @@ -248,8 +255,12 @@ public void run() { } // move that token ID to bottom of BNK00 file + JSONObject mineDetToSign = new JSONObject(); + try { - mineID = in.readLine(); + String mineData = in.readLine(); + // convert mineData to JSONObject + mineDetToSign = new JSONObject(mineData); } catch (SocketException e) { QuorumConsensusLogger.debug("Sender Input Stream Null - Stake ID details"); socket.close(); @@ -257,11 +268,24 @@ public void run() { executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - if (mineID != null) { - QuorumConsensusLogger.debug("Stake ID: " + mineID); - String mineIDSigned = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineID); - out.println(mineIDSigned); + if (mineDetToSign.length() > 0) { + JSONObject stakingSigns = new JSONObject(); + + QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); + + stakingSigns.put( + STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + tokenHash)); + stakingSigns.put( + MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + mineDetToSign.getString(MINING_TID))); + stakingSigns.put( + MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + mineDetToSign.getString(MINED_RBT))); + stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + mineDetToSign.getString(MINE_ID))); + + out.println(stakingSigns.toString()); } else { QuorumConsensusLogger.debug("Stake ID: Null"); } diff --git a/src/com/rubix/Constants/ConsensusConstants.java b/src/com/rubix/Constants/ConsensusConstants.java index b67e588c..21a5a34a 100644 --- a/src/com/rubix/Constants/ConsensusConstants.java +++ b/src/com/rubix/Constants/ConsensusConstants.java @@ -1,11 +1,10 @@ package com.rubix.Constants; - public class ConsensusConstants { public static final String TRANSACTION_ID = "Tid"; public static final String HASH = "Hash"; public static final String RECEIVERID = "RID"; - + public static final String MINE_XORER = "yhevnyxcwblibeikfagmazsldzkfgnqwmketmcubnuvlbb"; } diff --git a/src/com/rubix/Constants/MiningConstants.java b/src/com/rubix/Constants/MiningConstants.java new file mode 100644 index 00000000..ed53bcdc --- /dev/null +++ b/src/com/rubix/Constants/MiningConstants.java @@ -0,0 +1,14 @@ +package com.rubix.Constants; + +public class MiningConstants { + + public static final String MINING_TID = "mineTransactionID"; + public static final String MINED_RBT = "minedToken"; + public static final String MINE_ID = "mineID"; + public static final String STAKED_QUORUM_DID = "stakedQuorumDID"; + public static final String STAKED_TOKEN = "stakedToken"; + public static final String STAKED_TOKEN_SIGN = "stakedTokenSignature"; + public static final String MINING_TID_SIGN = "TIDSignature"; + public static final String MINED_RBT_SIGN = "minedTokenSignature"; + public static final String MINE_ID_SIGN = "mineIDSignature"; +} diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 2354ae8f..524889e0 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -489,61 +489,7 @@ public static void demoteToken(String tokenID) { } } - /** - * This function generate Stake ID for a pleadged token. mined token can also be - * found from stake ID - * - * @param stakedTokenID ID to be mined - * @param quorumDID ID to be mined - * @param minedTokenID ID to be mined - * @return Stake ID for that token - */ - public static String generateMineID(String stakedTokenID) { - String mineID = calculateHash("stake" + stakedTokenID, "SHA3-256"); - - return mineID; - } - - /** - * This function generate Stake ID for a pleadged token. mined token can also be - * found from stake ID - * - * @return mine ID for that token - */ - public static String minedTokenIDFromMineID(String mineID) { - String KEY = "mined"; - // ! multihash structure needed.. - String minedTokenID = calculateHash("stake" + mineID, "SHA3-256"); - return minedTokenID; - } - - /** - * This function generate Stake ID for a pleadged token. mined token can also be - * found from stake ID - * - * @return mine ID for that token - */ - public static String stakedQuorumDIDFromMineID(String mineID) { - String KEY = "staker"; - // ! multihash structure needed.. - String stakedQuorumDID = calculateHash("stake" + mineID, "SHA3-256"); - return stakedQuorumDID; - } - - /** - * This function generate Stake ID for a pleadged token. mined token can also be - * found from stake ID - * - * @return mine ID for that token - */ - public static String stakedTokenIDFromMineID(String mineID) { - String KEY = "staked"; - // ! multihash structure needed.. - String stakedTokenID = calculateHash("stake" + mineID, "SHA3-256"); - return stakedTokenID; - } - - public static int creditsRequiredForLevel() { + public static int levelHeight() { int creditsRequired = 0; JSONObject resJsonData_credit = new JSONObject(); String GET_URL_credit = SYNC_IP + "/getlevel"; diff --git a/src/com/rubix/Resources/IPFSNetwork.java b/src/com/rubix/Resources/IPFSNetwork.java index e7b90ead..fc877518 100644 --- a/src/com/rubix/Resources/IPFSNetwork.java +++ b/src/com/rubix/Resources/IPFSNetwork.java @@ -1,5 +1,6 @@ package com.rubix.Resources; +import static com.rubix.Constants.ConsensusConstants.MINE_XORER; import static com.rubix.Constants.IPFSConstants.bootstrap; import static com.rubix.Constants.IPFSConstants.daemon; import static com.rubix.Constants.IPFSConstants.forward; @@ -269,6 +270,17 @@ public static String addHashOnly(String fileName, IPFS ipfs) { return null; } + public static String getMineID(String stakedToken, IPFS ipfs) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < stakedToken.length(); i++) { + sb.append((char) (stakedToken.charAt(i) ^ MINE_XORER.charAt(i))); + } + // convert sb to IPFS multihash + String multihash = add(sb.toString(), ipfs); + + return multihash; + } + /** * This method pin objects to local storage See * ipfs pin diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 44c87d88..cd7b24c9 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -24,6 +24,7 @@ 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.getMineID; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.pin; import static com.rubix.Resources.IPFSNetwork.repo; @@ -275,39 +276,43 @@ public static String receive() { // ! starts mine ID check for (int i = 0; i < wholeTokens.length(); ++i) { + try { + + // ! STEP 1 : checking if any of the tokens are actively staked for mining + TokenReceiverLogger.debug("Checking mine ID for " + wholeTokens.getString(i) + " Please wait..."); - String mineID = "mineID"; + String mineID = getMineID(wholeTokens.getString(i).toString(), ipfs); stakeOwnersArray = IPFSNetwork.dhtOwnerCheck(mineID); - if (stakeOwnersArray.size() > 1) { + if (stakeOwnersArray.size() > 0) { // ! check sign on pinned mine ID - String minedToken = Functions.minedTokenIDFromMineID(mineID); + // JSONArray stakedTC = wholeTokenChains.getJSONArray(i); + // JSONObject stakeInfo = stakedTC.getJSONObject(1); - int minedTokenHeight = Functions.tokenHeightFromTokenID(minedToken); - if (minedTokenHeight < 32) { - incompleteStake = true; - } + // String minedToken = stakeInfo.getString(MINED_RBT); - // for (int j = 0; j < previousSendersArray.length(); j++) { - // if (previousSendersArray.getJSONObject(j).getString("token") - // .equals(wholeTokens.getString(i))) - // ownersReceived = - // previousSendersArray.getJSONObject(j).getJSONArray("sender"); - // } + // TokenReceiverLogger + // .debug("Checking owners and credits / signatures for mined token: " + + // minedToken + // + " Please wait..."); - // for (int j = 0; j < ownersReceived.length(); j++) { - // previousSender.add(ownersReceived.getString(j)); - // } - // TokenReceiverLogger.debug("Previous Owners: " + previousSender); + // String minedTC = get(minedToken, ipfs); - // for (int j = 0; j < ownersArray.size(); j++) { - // if (!previousSender.contains(ownersArray.get(j).toString())) - // tokenOwners = false; + // JSONArray minedTCArray = new JSONArray(minedTC); + + // if (minedTCArray.length() < 32) { + // incompleteStake = true; // } + + // TokenReceiverLogger.trace("Failed to fetch mined token chain"); + } + + // ! STEP 2 : checking if any of the tokens are newly minted to verify stake + } catch (IOException e) { TokenReceiverLogger.trace("Ipfs dht find did not execute (mineID check)"); @@ -318,7 +323,7 @@ public static String receive() { TokenReceiverLogger.debug("Token Height not reached for corresponding Staked Tokens " + stakedToken); output.println("425"); output.println(stakedToken.toString()); - output.println("stakes not complete"); + output.println("Stake Incomplete"); APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); From 7e2285611cb5191a9bbc80c6bd8ab033356c5c26 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 3 Mar 2022 11:56:37 +0530 Subject: [PATCH 011/179] combine whole token checks Signed-off-by: Nidhin Mahesh A --- .../rubix/TokenTransfer/TokenReceiver.java | 53 +++++++++---------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index cd7b24c9..e2d9a8d2 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -247,35 +247,8 @@ public static String receive() { TokenReceiverLogger.trace("Ipfs dht find did not execute (double spend check)"); } - } - - if (!tokenOwners) { - // JSONArray owners = new JSONArray(); - // for (int i = 0; i < ownersArray.size(); i++) - // owners.put(ownersArray.get(i).toString()); - // TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); - // TokenReceiverLogger.debug("Owners: " + owners); - // output.println("420"); - // output.println(doubleSpentToken.toString()); - // output.println(owners.toString()); - // APIResponse.put("did", senderDidIpfsHash); - // APIResponse.put("tid", "null"); - // APIResponse.put("status", "Failed"); - // APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + - // owners); - // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - // output.close(); - // input.close(); - // sk.close(); - // ss.close(); - // return APIResponse.toString(); - - TokenReceiverLogger.debug("Multiple Pins for " + doubleSpentToken); - } - // ! starts mine ID check - - for (int i = 0; i < wholeTokens.length(); ++i) { + // ! starts mine ID check try { @@ -319,6 +292,30 @@ public static String receive() { } } + if (!tokenOwners) { + // JSONArray owners = new JSONArray(); + // for (int i = 0; i < ownersArray.size(); i++) + // owners.put(ownersArray.get(i).toString()); + // TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); + // TokenReceiverLogger.debug("Owners: " + owners); + // output.println("420"); + // output.println(doubleSpentToken.toString()); + // output.println(owners.toString()); + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", "null"); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + + // owners); + // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + // output.close(); + // input.close(); + // sk.close(); + // ss.close(); + // return APIResponse.toString(); + + TokenReceiverLogger.debug("Multiple Pins for " + doubleSpentToken); + } + if (incompleteStake) { TokenReceiverLogger.debug("Token Height not reached for corresponding Staked Tokens " + stakedToken); output.println("425"); From 11b6380fa9004c883a0e2afeeedd38067d47773b Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 3 Mar 2022 15:35:39 +0530 Subject: [PATCH 012/179] Sanity & Receiver Check Integration Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 22 + .../rubix/Consensus/InitiatorProcedure.java | 1 + src/com/rubix/Consensus/QuorumConsensus.java | 24 +- src/com/rubix/Mining/ProofCredits.java | 8 - src/com/rubix/Ping/PingCheck.java | 97 +++ src/com/rubix/Ping/PingReceive.java | 102 +++ src/com/rubix/Ping/QuorumPingReceive.java | 102 +++ src/com/rubix/Resources/APIHandler.java | 697 +++++++++--------- src/com/rubix/Resources/Functions.java | 458 ++++++++---- src/com/rubix/Resources/IPFSNetwork.java | 7 +- .../rubix/TokenTransfer/TokenReceiver.java | 188 ++--- src/com/rubix/TokenTransfer/TokenSender.java | 121 +-- 12 files changed, 1165 insertions(+), 662 deletions(-) create mode 100644 src/com/rubix/Ping/PingCheck.java create mode 100644 src/com/rubix/Ping/PingReceive.java create mode 100644 src/com/rubix/Ping/QuorumPingReceive.java diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index f0286973..39dabe78 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -287,6 +287,28 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri } } } + + try { + qResponse[j] = qIn[j].readLine(); + } catch (SocketException e) { + InitiatorConsensusLogger + .warn("Quorum " + quorumID[j] + " is unable to Respond!"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); + } + + if (qResponse[j] != null) { + if (qResponse[j].equals("Auth_Failed")) { + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); + } else { + JSONObject signObject = new JSONObject(); + signObject.put("did", quorumID[j]); + signObject.put("hash", detailsToken.getString("ownerIdentity")); + signObject.put("signature", qResponse[j]); + ownerSigns.put(signObject); + + } + } + } else if (qResponse[j].equals("440")) { InitiatorConsensusLogger.debug("Credit Verification failed: Duplicates found"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); diff --git a/src/com/rubix/Consensus/InitiatorProcedure.java b/src/com/rubix/Consensus/InitiatorProcedure.java index 142364e4..a97bafc6 100644 --- a/src/com/rubix/Consensus/InitiatorProcedure.java +++ b/src/com/rubix/Consensus/InitiatorProcedure.java @@ -83,6 +83,7 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz data1.put(ConsensusConstants.TRANSACTION_ID, tid); data1.put(ConsensusConstants.HASH, authSenderByQuorumHash); data1.put(ConsensusConstants.RECEIVERID, receiverDidIpfs); + data1.put("ownerIdentity", dataObject.getString("ownerIdentity")); data2.put("Share1", Q1Share); data2.put("Share2", Q2Share); diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index e7b62572..1e667a8e 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -85,10 +85,9 @@ public QuorumConsensus(String role, int port) { public void run() { while (true) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - String peerID, transactionID, verifySenderHash, receiverDID, appName, initHash, senderPrivatePos, token, - stakingQuorumDID, - stakedToken, - senderDidIpfsHash = "", senderPID = ""; + String peerID, transactionID, verifySenderHash, receiverDID, appName, stakingQuorumDID, + stakedToken, senderPrivatePos, initHash, token, + senderDidIpfsHash = "", senderPID = "", ownerHash = ""; ServerSocket serverSocket = null; Socket socket = null; try { @@ -118,9 +117,7 @@ public void run() { serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - if (operation.equals("new-credits-mining")) { - QuorumConsensusLogger.debug("New Credits"); String getNewCreditsData = null; try { @@ -303,7 +300,6 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // ! operation for quorum staking token ends here } else QuorumConsensusLogger.debug("Old Credits Mining / Whole RBT Token Transfer"); - String getRecData = null; try { getRecData = in.readLine(); @@ -327,6 +323,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", transactionID = readSenderData.getString("Tid"); verifySenderHash = readSenderData.getString("Hash"); receiverDID = readSenderData.getString("RID"); + ownerHash = readSenderData.getString("ownerIdentity"); // ! additional info for the mining verification initHash = readSenderData.getString("initHash"); @@ -349,12 +346,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", senderDidIpfsHash); nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); - - // ! check if each quorum member is signing on the quorumHash (which now is - // sender + receiver hash) - // concat of sender hash and rec hash) - - String quorumHash = calculateHash(token + transactionID, "SHA3-256"); + String quorumHash = calculateHash(verifySenderHash.concat(receiverDID), "SHA3-256"); QuorumConsensusLogger.debug("1: " + verifySenderHash); QuorumConsensusLogger.debug("2: " + receiverDID); @@ -381,7 +373,6 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", QuorumConsensusLogger.debug("Quorum Authenticated Sender"); QuorumConsensusLogger.debug("ConsensusID pass"); - // json obj called quorumSignss JSONObject quorumSigns = new JSONObject(); @@ -402,6 +393,8 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", out.println(quorumSigns.toString()); + String ownerSign = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", ownerHash); + String creditSignatures = null; try { creditSignatures = in.readLine(); @@ -449,14 +442,13 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", deleteFile(LOGGER_PATH + "consenusIDhash"); QuorumConsensusLogger.debug("added consensus ID " + consenusIDhash); } + out.println(ownerSign); } else { QuorumConsensusLogger.debug("Sender Authentication Failure - Quorum"); out.println("Auth_Failed"); } - // ! moving staked token to bottom of BNK00 file. - } } else { QuorumConsensusLogger.debug("Quorum - " + didHash + " is unable to respond!" + getRecData); diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 1e1d9ec3..dbd948c0 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -14,7 +14,6 @@ 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.initHash; import static com.rubix.Resources.Functions.minQuorum; import static com.rubix.Resources.Functions.mineUpdate; import static com.rubix.Resources.Functions.readFile; @@ -272,7 +271,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON dataObject.put("alphaList", alphaPeersList); dataObject.put("betaList", betaPeersList); dataObject.put("gammaList", gammaPeersList); - dataObject.put("initHash", initHash()); dataObject.put("qstDetails", qstObject); InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 3, alphaSize, @@ -345,12 +343,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); deleteFile(LOGGER_PATH + "tempToken"); writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", "[]", false); - // genesis signatures - updateJSON("add", TOKENCHAIN_PATH + tokenHash + ".json", - InitiatorConsensus.quorumSignature.toString()); - // staking signatures - updateJSON("add", TOKENCHAIN_PATH + tokenHash + ".json", - InitiatorConsensus.stakingSignature.toString()); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); JSONArray tempArray = new JSONArray(); diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java new file mode 100644 index 00000000..c8f8ef1e --- /dev/null +++ b/src/com/rubix/Ping/PingCheck.java @@ -0,0 +1,97 @@ +package com.rubix.Ping; + +import io.ipfs.api.IPFS; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONException; +import org.json.JSONObject; +import java.io.*; +import java.net.Socket; +import java.net.SocketException; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.IPFSNetwork.*; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; + +public class PingCheck { + private static final Logger PingSenderLogger = Logger.getLogger(PingCheck.class); + public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + public static BufferedReader serverInput; + + + public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { + repo(ipfs); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + JSONObject APIResponse = new JSONObject(); + if (!peerID.equals("")) { + PingSenderLogger.debug("Swarm connecting to " + peerID); + swarmConnectP2P(peerID, ipfs); + PingSenderLogger.debug("Swarm connected"); + } else { + APIResponse.put("message", "Receiver Peer ID null"); + PingSenderLogger.warn("Receiver Peer ID null"); + return APIResponse; + } + + String receiverWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "peerid", peerID); + String receiverDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID); + if (!receiverWidIpfsHash.equals("")) { + nodeData(receiverDidIpfsHash, receiverWidIpfsHash, ipfs); + } else { + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Receiver WID null"); + PingSenderLogger.warn("Receiver WID null"); + return APIResponse; + } + + PingSenderLogger.debug("Sender IPFS forwarding to DID: " + receiverDidIpfsHash + " PeerID: " + peerID); + String appName = peerID.concat("Ping"); + forward(appName, port, peerID); + PingSenderLogger.debug("Forwarded to " + appName + " on " + port); + Socket senderSocket = new Socket("127.0.0.1", port); + + BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); + PrintStream output = new PrintStream(senderSocket.getOutputStream()); + + output.println("PingCheck"); + PingSenderLogger.debug("Sent PingCheck request"); + + String pongResponse; + try { + pongResponse = input.readLine(); + } catch (SocketException e) { + PingSenderLogger.warn("Receiver " + receiverDidIpfsHash + " is unable to Respond! - Ping Check"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Receiver " + receiverDidIpfsHash + "is unable to respond! - Sender Auth"); + + return APIResponse; + } + + + if (pongResponse != null && (!pongResponse.equals("Pong"))) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + PingSenderLogger.info("Pong response not received"); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Pong response not received"); + + }else { + PingSenderLogger.info("Ping Successful"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Success"); + APIResponse.put("message", "Ping Check Success"); + + } + return APIResponse; + } +} diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java new file mode 100644 index 00000000..de4a0cf0 --- /dev/null +++ b/src/com/rubix/Ping/PingReceive.java @@ -0,0 +1,102 @@ +package com.rubix.Ping; + +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.getPeerID; +import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.listen; +import static com.rubix.Resources.IPFSNetwork.repo; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; + +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 PingReceive { + public static Logger PingReceiverLogger = Logger.getLogger(PingReceive.class); + + private static final JSONObject APIResponse = new JSONObject(); + private static final IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + + /** + * Receiver Node: To receive a valid token from an authentic sender + * + * @return Transaction Details (JSONObject) + * @throws IOException handles IO Exceptions + * @throws JSONException handles JSON Exceptions + */ + public static String receive(int port) throws JSONException { + pathSet(); + ServerSocket ss; + Socket sk; + + try { + repo(ipfs); + + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); + String appName = receiverPeerID.concat("Ping"); + listen(appName, port); + ss = new ServerSocket(port); + PingReceiverLogger.debug("Ping Receiver Listening on " + port + " appname " + appName); + + sk = ss.accept(); + PingReceiverLogger.debug("Data Incoming..."); + BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); + PrintStream output = new PrintStream(sk.getOutputStream()); + + String pingRequest; + try { + pingRequest = input.readLine(); + } catch (SocketException e) { + PingReceiverLogger.warn("Sender Stream Null - PingCheck"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - PingCheck"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + PingReceiverLogger.debug("Ping Request Received: " + pingRequest); + if (pingRequest != null && pingRequest.contains("PingCheck")) { + output.println("Pong"); + + APIResponse.put("status", "Success"); + APIResponse.put("message", "Pong Sent"); + PingReceiverLogger.info("Pong Sent"); + + } else { + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Pong Failed"); + PingReceiverLogger.info("Pong Failed"); + } + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pingRequest); + output.close(); + input.close(); + sk.close(); + ss.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + return APIResponse.toString(); + } +} diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java new file mode 100644 index 00000000..354315df --- /dev/null +++ b/src/com/rubix/Ping/QuorumPingReceive.java @@ -0,0 +1,102 @@ +package com.rubix.Ping; + +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.getPeerID; +import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.listen; +import static com.rubix.Resources.IPFSNetwork.repo; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; + +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 QuorumPingReceive { + public static Logger QuorumPingReceiverLogger = Logger.getLogger(QuorumPingReceive.class); + + private static final JSONObject APIResponse = new JSONObject(); + private static final IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + + /** + * Receiver Node: To receive a valid token from an authentic sender + * + * @return Transaction Details (JSONObject) + * @throws IOException handles IO Exceptions + * @throws JSONException handles JSON Exceptions + */ + public static String receive(int port) throws JSONException { + pathSet(); + ServerSocket ss; + Socket sk; + + try { + repo(ipfs); + + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); + String appName = receiverPeerID.concat("Ping"); + listen(appName, port); + ss = new ServerSocket(port); + QuorumPingReceiverLogger.debug("Ping Quorum Listening on " + port + " appname " + appName); + + sk = ss.accept(); + QuorumPingReceiverLogger.debug("Data Incoming..."); + BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); + PrintStream output = new PrintStream(sk.getOutputStream()); + + String pingRequest; + try { + pingRequest = input.readLine(); + } catch (SocketException e) { + QuorumPingReceiverLogger.warn("Sender Stream Null - PingCheck"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - PingCheck"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + QuorumPingReceiverLogger.debug("Ping Request Received: " + pingRequest); + if (pingRequest != null && pingRequest.contains("PingCheck")) { + output.println("Pong"); + + APIResponse.put("status", "Success"); + APIResponse.put("message", "Pong Sent"); + QuorumPingReceiverLogger.info("Pong Sent"); + + } else { + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Pong Failed"); + QuorumPingReceiverLogger.info("Pong Failed"); + } + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pingRequest); + output.close(); + input.close(); + sk.close(); + ss.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + return APIResponse.toString(); + } +} diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 14e22c13..a21bcc8e 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -135,42 +135,203 @@ public static JSONObject create(int type) throws Exception { } /** - * A call to get details of a transaction given its ID + * A method to add and host your DID ans Public share to ipfs * - * @param txnId - * @return Transaction Details - * @throws JSONException handles JSON Exceptions + * @files DID.json, DataTable.json, DID.png, PublicShare.png */ - public static JSONArray transactionDetails(String txnId) throws JSONException { - String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); - JSONObject countResult = new JSONObject(); + 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); + + } + + /** + * A call to sync all the nodes in the network + * + * @return Message if failed or succeeded + * @throws IOException + * @files DataTable.json + */ + public static String networkInfo() throws IOException, JSONException { + StringBuilder result = new StringBuilder(); JSONArray resultArray = new JSONArray(); - if (transactionHistory.length() == 0) { - countResult.put("Message", "No transactions found"); - resultArray.put(countResult); - return resultArray; + JSONObject jsonObject = new JSONObject(); + int syncFlag = 0; + URL url = new URL(SYNC_IP + "/get"); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + + while ((line = rd.readLine()) != null) { + result.append(line); + syncFlag = 1; } - JSONArray transArray = new JSONArray(transactionHistory); - JSONObject obj = new JSONObject(); - for (int i = 0; i < transArray.length(); i++) { - obj = transArray.getJSONObject(i); - if (obj.get("txn").equals(txnId)) { - obj.remove("essentialShare"); + rd.close(); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); - else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); - } + writeToFile(DATA_PATH + "DataTable.json", result.toString(), false); + if (syncFlag == 1) { + jsonObject.put("message", "Synced Successfully!"); + } else { + jsonObject.put("message", "Not synced! Try again after sometime."); + } + resultArray.put(jsonObject); + return resultArray.toString(); + } - resultArray.put(obj); + /** + * Method to query the credits information + * + * @throws JSONException + * + * @files QuorumSignedTransactions.json, MinedCreditsHistory.json + */ + public static JSONObject creditsInfo() throws JSONException { + String qstFile = WALLET_DATA_PATH.concat("QuorumSignedTransactions.json"); + String mineFile = WALLET_DATA_PATH.concat("MinedCreditsHistory.json"); + + File quorumFile = new File(qstFile); + File minedFile = new File(mineFile); + + int spentCredits = 0; + int unspentCredits = 0; + if (quorumFile.exists()) { + String qFile = readFile(qstFile); + JSONArray qArray = new JSONArray(qFile); + unspentCredits = qArray.length(); + } + if (minedFile.exists()) { + String mFile = readFile(mineFile); + JSONArray mArray = new JSONArray(mFile); + spentCredits = mArray.length(); + } + + JSONObject returnObject = new JSONObject(); + returnObject.put("spentCredits", spentCredits); + returnObject.put("unspentCredits", unspentCredits); + + return returnObject; + } + + /** + * A call to close all open IPFS streams + */ + public static void closeStreams() { + executeIPFSCommands("ipfs p2p close --all"); + } + + 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")) + count++; + } + return count; + } + + public static ArrayList swarmPeersList() throws IOException, InterruptedException { + String OS = getOsName(); + String[] command = new String[3]; + if (OS.contains("Mac") || OS.contains("Linux")) { + command[0] = "bash"; + command[1] = "-c"; + } else if (OS.contains("Windows")) { + command[0] = "cmd.exe"; + command[1] = "/c"; + } + command[2] = "export PATH=/usr/local/bin:$PATH && ipfs swarm peers"; + + Process P = Runtime.getRuntime().exec(command); + BufferedReader br = new BufferedReader(new InputStreamReader(P.getInputStream())); + + ArrayList peersArray = new ArrayList(); + String line; + while ((line = br.readLine()) != null) { + peersArray.add(line); + } + if (!OS.contains("Windows")) + P.waitFor(); + br.close(); + P.destroy(); + + ArrayList peersIdentities = new ArrayList(); + if (peersArray.size() != 0) { + List k = ipfs.swarm.peers(); + 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 + */ + public static JSONArray peersOnlineStatus() throws JSONException, IOException, InterruptedException { + ArrayList peersArray = swarmPeersList(); + String dataTable = readFile(DATA_PATH + "DataTable.json"); + JSONArray dataArray = new JSONArray(dataTable); + JSONArray onlinePeers = new JSONArray(); + + for (int i = 0; i < dataArray.length(); i++) { + JSONObject peerObject = dataArray.getJSONObject(i); + String peerID = peerObject.getString("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 { + JSONObject onlinePeersObject = new JSONObject(); + onlinePeersObject.put("did", getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID)); + onlinePeersObject.put("onlineStatus", "offline"); + onlinePeers.put(onlinePeersObject); } } - APILogger.info("Transaction Details for : " + obj.toString()); - return resultArray; + + return onlinePeers; + } + + /** + * A call to list out all contacts in the user wallet + * + * @return A list of user wallet contacts + * @throws JSONException handles JSON Exceptions + */ + 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++) { + didArray.put(dataArray.getJSONObject(i).getString("didHash")); + } + return didArray; + } + + public static JSONObject syncNetworkNodes() throws JSONException, IOException { + String dataTable = readFile(DATA_PATH + "DataTable.json"); + 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); + + return new JSONObject("{\"message\":\"Synced all nodes\"}"); } /** @@ -178,6 +339,7 @@ public static JSONArray transactionDetails(String txnId) throws JSONException { * * @return Detailed explanation of the account information of the user * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json, DID.json */ public static JSONArray accountInformation() throws JSONException { int txnAsSender = 0, txnAsReceiver = 0; @@ -219,53 +381,80 @@ public static JSONArray accountInformation() throws JSONException { } /** - * A method to add and host your DID ans Public share to ipfs + * A call to list out number of transactions made per day + * + * @return List of transactions committed on every date + * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ - 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); + public static JSONArray txnPerDay() throws JSONException { + String dataTableFileContent = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); + JSONArray dataTable = new JSONArray(dataTableFileContent); + HashSet dateSet = new HashSet<>(); + for (int i = 0; i < dataTable.length(); i++) + dateSet.add(dataTable.getJSONObject(i).getString("Date")); - add(DATA_PATH.concat(didHash).concat("/DID.png"), ipfs); - pin(didHash, ipfs); + JSONObject datesTxn = new JSONObject(); + Iterator dateIterator = dateSet.iterator(); + while (dateIterator.hasNext()) { + String date = dateIterator.next(); + int count = 0; + for (int i = 0; i < dataTable.length(); i++) { + JSONObject obj = dataTable.getJSONObject(i); - add(DATA_PATH.concat(didHash).concat("/PublicShare.png"), ipfs); - pin(walletHash, ipfs); + if (date.equals(obj.getString("Date"))) { + count++; + } + } + datesTxn.put(date, count); + + } + return new JSONArray().put(datesTxn); } /** - * A call to sync all the nodes in the network + * A call to get details of a transaction given its ID * - * @return Message if failed or succeeded - * @throws IOException + * @param txnId Transaction ID + * @return Transaction Details + * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ - public static String networkInfo() throws IOException, JSONException { - StringBuilder result = new StringBuilder(); + public static JSONArray transactionDetails(String txnId) throws JSONException { + String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); + JSONObject countResult = new JSONObject(); JSONArray resultArray = new JSONArray(); - JSONObject jsonObject = new JSONObject(); - int syncFlag = 0; - URL url = new URL(SYNC_IP + "/get"); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - - while ((line = rd.readLine()) != null) { - result.append(line); - syncFlag = 1; + if (transactionHistory.length() == 0) { + countResult.put("Message", "No transactions found"); + resultArray.put(countResult); + return resultArray; } - rd.close(); + JSONArray transactionArray = new JSONArray(transactionHistory); + JSONObject transactionObject = new JSONObject(); + for (int i = 0; i < transactionArray.length(); i++) { + transactionObject = transactionArray.getJSONObject(i); + if (transactionObject.get("txn").equals(txnId)) { + transactionObject.remove("essentialShare"); + + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); + else { + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); + } + + resultArray.put(transactionObject); + } - writeToFile(DATA_PATH + "DataTable.json", result.toString(), false); - if (syncFlag == 1) { - jsonObject.put("message", "Synced Successfully!"); - } else { - jsonObject.put("message", "Not synced! Try again after sometime."); } - resultArray.put(jsonObject); - return resultArray.toString(); + APILogger.info("Transaction Details for : " + transactionObject.toString()); + return resultArray; } /** @@ -275,6 +464,7 @@ public static String networkInfo() throws IOException, JSONException { * @param e End Date * @return List of transactions * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ public static JSONArray transactionsByDate(String s, String e) throws JSONException, ParseException { JSONArray resultArray = new JSONArray(); @@ -287,8 +477,6 @@ public static JSONArray transactionsByDate(String s, String e) throws JSONExcept JSONObject countResult = new JSONObject(); Date startDate = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").parse(startDateString); Date endDate = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").parse(endDateString); - APILogger.debug("start date is " + startDate); - APILogger.debug("end date is " + endDate); File fileCheck1 = new File(WALLET_DATA_PATH + "TransactionHistory.json"); if (!fileCheck1.exists()) { countResult.put("Message", "File not found"); @@ -297,32 +485,37 @@ public static JSONArray transactionsByDate(String s, String e) throws JSONExcept } String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); - APILogger.debug(transArray.length()); if (transArray.length() == 0) { countResult.put("Message", "No Transactions made yet"); resultArray.put(countResult); return resultArray; } - JSONObject obj; + JSONObject transactionObject; for (int i = 0; i < transArray.length(); i++) { - obj = transArray.getJSONObject(i); - String dateFromTxnHistoryString = obj.get("Date").toString(); - Date dateTH = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(dateFromTxnHistoryString); - String dateTHS = objSDF.format(dateTH); - Calendar c = Calendar.getInstance(); - c.setTime(objSDF.parse(dateTHS)); - dateTH = c.getTime(); - if (dateTH.after(startDate) && dateTH.before(endDate)) { - obj.remove("essentialShare"); - - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); - else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + transactionObject = transArray.getJSONObject(i); + String dateFromTxnHistoryString = transactionObject.get("Date").toString(); + if (dateFromTxnHistoryString.length() != 10) { + Date dateTH = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(dateFromTxnHistoryString); + String dateTHS = objSDF.format(dateTH); + Calendar c = Calendar.getInstance(); + c.setTime(objSDF.parse(dateTHS)); + dateTH = c.getTime(); + if (dateTH.after(startDate) && dateTH.before(endDate)) { + transactionObject.remove("essentialShare"); + + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); + else { + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); + } + + resultArray.put(transactionObject); } - - resultArray.put(obj); } } @@ -335,6 +528,7 @@ public static JSONArray transactionsByDate(String s, String e) throws JSONExcept * @param n Count * @return List of transactions * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ public static JSONArray transactionsByCount(int n) throws JSONException { @@ -351,7 +545,7 @@ public static JSONArray transactionsByCount(int n) throws JSONException { } String transactionHistory = readFile(path); JSONArray transArray = new JSONArray(transactionHistory); - JSONObject obj = new JSONObject(); + JSONObject transactionObject; if (transArray.length() == 0) { countResult.put("Message", "No transactions made yet"); resultArray.put(countResult); @@ -360,31 +554,39 @@ public static JSONArray transactionsByCount(int n) throws JSONException { if (n >= transArray.length()) { for (int i = transArray.length() - 1; i >= 0; i--) { - obj = transArray.getJSONObject(i); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + transactionObject = transArray.getJSONObject(i); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - resultArray.put(obj); + resultArray.put(transactionObject); } return resultArray; } for (int i = 1; i <= n; i++) { - obj = transArray.getJSONObject(transArray.length() - i); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + transactionObject = transArray.getJSONObject(transArray.length() - i); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - resultArray.put(obj); + resultArray.put(transactionObject); } return resultArray; } @@ -396,11 +598,12 @@ public static JSONArray transactionsByCount(int n) throws JSONException { * @param end end index * @return List of transactions * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ public static JSONArray transactionsByRange(int start, int end) throws JSONException { JSONObject countResult = new JSONObject(); JSONArray resultArray = new JSONArray(); - if (start <= 0 || end <= 0) { + if (start < 0 || end <= 0) { countResult.put("Message", "Count can't be null or negative"); resultArray.put(countResult); return resultArray; @@ -427,122 +630,89 @@ public static JSONArray transactionsByRange(int start, int end) throws JSONExcep if (!(end < transArray.length())) { for (int i = start; i < transArray.length(); i++) { - JSONObject obj = transArray.getJSONObject(i); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + JSONObject transactionObject = transArray.getJSONObject(i); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - resultArray.put(obj); + resultArray.put(transactionObject); } } else { if (start == end) { - JSONObject obj = transArray.getJSONObject(start); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + JSONObject transactionObject = transArray.getJSONObject(start); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - resultArray.put(obj); - } - for (int i = start; i < end; i++) { - JSONObject obj = transArray.getJSONObject(i); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); - else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + resultArray.put(transactionObject); + } else { + for (int i = start; i <= end; i++) { + JSONObject transactionObject = transArray.getJSONObject(i); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); + else { + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); + } + resultArray.put(transactionObject); } - - resultArray.put(obj); } } return resultArray; } - /** - * @throws JSONException - * - */ - public static JSONObject creditsInfo() throws JSONException { - // String thFile = WALLET_DATA_PATH.concat("TransactionHistory.json"); - String qstFile = WALLET_DATA_PATH.concat("QuorumSignedTransactions.json"); - String mineFile = WALLET_DATA_PATH.concat("MinedCreditsHistory.json"); - - // File txnFile = new File(thFile); - File quorumFile = new File(qstFile); - File minedFile = new File(mineFile); - - // int txnCount = 0; - // if(txnFile.exists()){ - // String transactionFile = - // readFile(WALLET_DATA_PATH.concat("TransactionHistory.json")); - // JSONArray txnArray = new JSONArray(transactionFile); - // txnCount = txnArray.length(); - // - // } - int spentCredits = 0; - int unspentCredits = 0; - if (quorumFile.exists()) { - String qFile = readFile(qstFile); - JSONArray qArray = new JSONArray(qFile); - unspentCredits = qArray.length(); - } - if (minedFile.exists()) { - String mFile = readFile(mineFile); - JSONArray mArray = new JSONArray(mFile); - spentCredits = mArray.length(); - } - - JSONObject returnObject = new JSONObject(); - // returnObject.put("txnCount",txnCount); - returnObject.put("spentCredits", spentCredits); - returnObject.put("unspentCredits", unspentCredits); - - return returnObject; - } - - /** - * A call to close all open IPFS streams - */ - 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 + * @files TransactionHistory.json */ public static JSONArray transactionsByComment(String comment) throws JSONException { String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); - JSONObject obj; + JSONObject transactionObject; JSONArray resultArray = new JSONArray(); for (int i = 0; i < transArray.length(); i++) { - obj = transArray.getJSONObject(i); - - if (obj.get("comment").equals(comment)) { - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + transactionObject = transArray.getJSONObject(i); + + if (transactionObject.get("comment").equals(comment)) { + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - - resultArray.put(obj); + resultArray.put(transactionObject); } } @@ -561,166 +731,33 @@ public static JSONArray transactionsByComment(String comment) throws JSONExcepti * @param did DID of the contact * @return List of transactions committed with the user DID * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ public static JSONArray transactionsByDID(String did) throws JSONException { String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); JSONArray resultArray = new JSONArray(); for (int i = 0; i < transArray.length(); i++) { - JSONObject obj = transArray.getJSONObject(i); - obj.remove("essentialShare"); + JSONObject transactionObject = transArray.getJSONObject(i); + transactionObject.remove("essentialShare"); + + if (transactionObject.get("senderDID").equals(did) || transactionObject.get("receiverDID").equals(did)) { + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); + else { + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); + } - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); - else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + resultArray.put(transactionObject); } - - resultArray.put(obj); - - if (obj.get("senderDID").equals(did) || obj.get("receiverDID").equals(did)) - resultArray.put(obj); } return resultArray; } - public static int onlinePeersCount() throws JSONException, IOException, InterruptedException { - JSONArray peersArray = peersOnlineStatus(); - int count = 0; - for (int i = 0; i < peersArray.length(); i++) { - if (peersArray.getJSONObject(i).getString("onlineStatus").contains("online")) - count++; - } - return count; - } - - public static ArrayList swarmPeersList() throws IOException, InterruptedException { - String OS = getOsName(); - String[] command = new String[3]; - if (OS.contains("Mac") || OS.contains("Linux")) { - command[0] = "bash"; - command[1] = "-c"; - } else if (OS.contains("Windows")) { - command[0] = "cmd.exe"; - command[1] = "/c"; - } - command[2] = "export PATH=/usr/local/bin:$PATH && ipfs swarm peers"; - - Process P = Runtime.getRuntime().exec(command); - BufferedReader br = new BufferedReader(new InputStreamReader(P.getInputStream())); - - ArrayList peersArray = new ArrayList(); - String line; - while ((line = br.readLine()) != null) { - peersArray.add(line); - } - if (!OS.contains("Windows")) - P.waitFor(); - br.close(); - P.destroy(); - - ArrayList peersIdentities = new ArrayList(); - if (peersArray.size() != 0) { - List k = ipfs.swarm.peers(); - 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 - */ - public static JSONArray peersOnlineStatus() throws JSONException, IOException, InterruptedException { - ArrayList peersArray = swarmPeersList(); - String dataTable = readFile(DATA_PATH + "DataTable.json"); - JSONArray dataArray = new JSONArray(dataTable); - JSONArray onlinePeers = new JSONArray(); - - for (int i = 0; i < dataArray.length(); i++) { - JSONObject peerObject = dataArray.getJSONObject(i); - String peerID = peerObject.getString("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 { - JSONObject onlinePeersObject = new JSONObject(); - onlinePeersObject.put("did", getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID)); - onlinePeersObject.put("onlineStatus", "offline"); - onlinePeers.put(onlinePeersObject); - } - - } - - return onlinePeers; - } - - /** - * A call to list out all contacts in the user wallet - * - * @return A list of user wallet contacts - * @throws JSONException handles JSON Exceptions - */ - 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++) { - didArray.put(dataArray.getJSONObject(i).getString("didHash")); - } - return didArray; - } - - /** - * A call to list out number of transactions made per day - * - * @return List of transactions committed on every date - * @throws JSONException handles JSON Exceptions - */ - 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++) - dateSet.add(dataArray.getJSONObject(i).getString("Date")); - - JSONObject datesTxn = new JSONObject(); - Iterator dateIterator = dateSet.iterator(); - while (dateIterator.hasNext()) { - String date = dateIterator.next(); - int count = 0; - for (int i = 0; i < dataArray.length(); i++) { - JSONObject obj = dataArray.getJSONObject(i); - - if (date.equals(obj.getString("Date"))) { - count++; - } - } - datesTxn.put(date, count); - - } - - return new JSONArray().put(datesTxn); - } - - public static JSONObject syncNetworkNodes() throws JSONException, IOException { - String dataTable = readFile(DATA_PATH + "DataTable.json"); - 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); - - return new JSONObject("{\"message\":\"Synced all nodes\"}"); - } } diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 524889e0..6cbd8875 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1,11 +1,14 @@ package com.rubix.Resources; import static com.rubix.Resources.APIHandler.addPublicData; +import static com.rubix.Resources.IPFSNetwork.IPFSNetworkLogger; import static com.rubix.Resources.IPFSNetwork.checkSwarmConnect; import static com.rubix.Resources.IPFSNetwork.dhtOwnerCheck; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.forwardCheck; import static com.rubix.Resources.IPFSNetwork.listen; +import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; +import static com.rubix.Resources.IPFSNetwork.swarmConnectProcess; import java.awt.image.BufferedImage; import java.io.BufferedReader; @@ -34,6 +37,7 @@ import javax.imageio.ImageIO; import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Ping.PingCheck; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; @@ -42,6 +46,7 @@ import org.json.JSONObject; import io.ipfs.api.IPFS; +import io.ipfs.multiaddr.MultiAddress; public class Functions { @@ -455,40 +460,6 @@ public static boolean checkTokenOwnershiByDID(String tokenID, String DID) { return ownStatus; } - /** - * Move the selected token to bottom of the BNK00 file to avoid transaction - * failures. - * - * @param tokenID ID to be minedD to be mined - * @return null - */ - public static void demoteToken(String tokenID) { - - try { - String bankNew = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray bankNewArray = new JSONArray(bankNew); - - JSONObject tokeJsonObject = new JSONObject(); - tokeJsonObject.put("tokenHash", tokenID); - - // remove tokenJsonObject from bankNewArray - for (int i = 0; i < bankNewArray.length(); i++) { - JSONObject temp = bankNewArray.getJSONObject(i); - if (temp.getString("tokenHash").equals(tokenID)) { - bankNewArray.remove(i); - break; - } - } - bankNewArray.put(tokeJsonObject); - - // write the new bankNewArray to file - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankNewArray.toString(), false); - - } catch (JSONException e) { - FunctionsLogger.error("JSONException Occurred", e); - } - } - public static int levelHeight() { int creditsRequired = 0; JSONObject resJsonData_credit = new JSONObject(); @@ -526,48 +497,6 @@ public static int levelHeight() { return creditsRequired; } - /** - * This function calculates token height from tokenchain for the given token id - * (without considering ownership) - * found from stake ID - * - * @param token ID to be staked - * @return Stake ID for that token - */ - - public static int tokenHeightFromTokenID(String tokenID) { - - // height for current level x2 - int requiredHeight = 64; - - // ! get data from DID server or contact owner of mined token for token height - - return requiredHeight; - } - - /** - * This function check Stake ID for a pleadged token. mined token can also be - * found from stake ID - * - * @param token ID to be staked - * @return boolean of exists or not - */ - public static boolean checkMineIDExists(String tokenID) { - boolean mineIDExists = false; - String mineID = calculateHash("stake" + tokenID, "SHA3-256"); - mineIDExists = checkTokenOwnershiByDID(mineID, mineID); - try { - ArrayList owners = dhtOwnerCheck(tokenID); - if (!owners.isEmpty()) { - mineIDExists = true; - } - - } catch (InterruptedException | JSONException | IOException e) { - FunctionsLogger.error("JSONException Occurred while - checkMineIDExists - check", e); - } - return mineIDExists; - } - /** * This function converts any integer to its binary form * @@ -1016,8 +945,7 @@ public static String checkDirectory() throws JSONException { // File pvtImage = new File(DATA_PATH + myDID + "/PrivateShare.png"); if (!didImage.exists() || !widImage.exists()) { didImage.delete(); - didImage.delete(); - didImage.delete(); + widImage.delete(); JSONObject result = new JSONObject(); result.put("message", "User not registered, create your Decentralised Identity!"); result.put("info", "Shares Images Missing"); @@ -1286,89 +1214,34 @@ public static void syncDataTable(String did, String peerId) { } } - /** - * This function will release the port in linux based machines if the port is - * already in use - */ - public static void releasePorts(int port) { - String processStr; - Process processId; - try { - processId = Runtime.getRuntime().exec("lsof -ti :" + port); - long currentPid = ProcessHandle.current().pid(); - BufferedReader br = new BufferedReader( - new InputStreamReader(processId.getInputStream())); - - processId = Runtime.getRuntime().exec("pgrep ipfs"); - BufferedReader ipfsPidBr = new BufferedReader(new InputStreamReader(processId.getInputStream())); - - processStr = br.readLine(); - while (processStr != null - && (String.valueOf(currentPid) != processStr || (ipfsPidBr.readLine() != processStr))) { - FunctionsLogger.debug("Port " + port + " is in using, killing PID " + processStr); - processId = Runtime.getRuntime().exec("kill -9 " + processStr); + public static void correctToken() throws JSONException { + pathSet(); + String bank = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bankArray = new JSONArray(bank); + JSONObject firstToken; + if (bankArray.length() > 1) { + firstToken = bankArray.getJSONObject(0); - } - processId.waitFor(); - processId.destroy(); + bankArray.remove(0); + bankArray.put(firstToken); - } catch (Exception e) { - FunctionsLogger.error("Exception Occured at releasePort", e); - e.printStackTrace(); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); } } - public static void portStatusWindows(int port) { - String processStr; - Process p; - try { - Runtime rt = Runtime.getRuntime(); - Process proc = rt.exec("cmd /c netstat -ano | findstr " + port); - long currentPid = ProcessHandle.current().pid(); - BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); - processStr = stdInput.readLine(); - if (processStr != null && String.valueOf(currentPid) != processStr) { - int index = processStr.lastIndexOf(" "); - String sc = processStr.substring(index, processStr.length()); - // System.out.println("Port "+port+" is locked by PID "+sc+". Kindly close this - // port and retry transcation"); - if (sc != String.valueOf(currentPid)) { - FunctionsLogger.debug("Port " + port + " is locked by PID " + sc); - } else { - FunctionsLogger.debug("Port " + port + " is locked by current jar with PID " + sc); - } - - } - } catch (Exception e) { - FunctionsLogger.error("Exception occured at portStatusWindows", e); - e.printStackTrace(); - } - } + public static void correctPartToken() throws JSONException { + pathSet(); + String bank = readFile(PAYMENTS_PATH.concat("PartsToken.json")); + JSONArray bankArray = new JSONArray(bank); + JSONObject firstToken; + if (bankArray.length() > 1) { + firstToken = bankArray.getJSONObject(0); - public static void removeToken() throws JSONException { - String bnkFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray bnkArray = new JSONArray(bnkFile); - JSONObject removeToken = bnkArray.getJSONObject(0); - bnkArray.remove(0); - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bnkArray.toString(), false); + bankArray.remove(0); + bankArray.put(firstToken); - File doubleSpentFile = new File(PAYMENTS_PATH.concat("DoubleSpent.json")); - if (!doubleSpentFile.exists()) { - try { - doubleSpentFile.createNewFile(); - } catch (IOException e) { - FunctionsLogger.debug("File couldn't be created"); - } - JSONArray removeArray = new JSONArray(); - removeArray.put(removeToken); - writeToFile(PAYMENTS_PATH.concat("DoubleSpent.json"), removeArray.toString(), false); - } else { - String removeFile = readFile(PAYMENTS_PATH.concat("DoubleSpent.json")); - JSONArray removeArray = new JSONArray(removeFile); - removeArray.put(removeToken); - writeToFile(PAYMENTS_PATH.concat("DoubleSpent.json"), removeArray.toString(), false); + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), bankArray.toString(), false); } - } public static void tokenBank() throws JSONException { @@ -1665,4 +1538,283 @@ public static void backgroundChecks() { } + public static String sanityMessage; + + public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOException, JSONException { + FunctionsLogger.info("Entering SanityCheck"); + boolean sanityCheckErrorFlag = true; + if (sanityCheckErrorFlag && checkIPFSStatus(peerid, ipfs)) { + FunctionsLogger.debug("IPFS is working in " + peerid); + FunctionsLogger.debug("IPFS check true"); + } else { + sanityCheckErrorFlag = false; + FunctionsLogger.debug("IPFS is not working in " + peerid); + FunctionsLogger.debug("IPFS check false"); + sanityMessage = "IPFS is not working in " + peerid; + } + + if (sanityCheckErrorFlag) { + if (bootstrapConnect(peerid, ipfs)) { + FunctionsLogger.debug("Bootstrap connected for " + peerid); + FunctionsLogger.debug("Bootstrap check true"); + } else { + sanityCheckErrorFlag = false; + FunctionsLogger.debug("Bootstrap connection unsuccessful for " + peerid); + FunctionsLogger.debug("Bootstrap check false"); + sanityMessage = "Bootstrap connection unsuccessful for " + peerid; + } + } + + if (sanityCheckErrorFlag) { + if (ping(peerid, port)) { + FunctionsLogger.debug("Jar is running as expected in " + peerid); + FunctionsLogger.debug("Jar check true"); + } else { + sanityCheckErrorFlag = false; + FunctionsLogger.debug("Jar is not running in " + peerid); + FunctionsLogger.debug("Jar check false"); + sanityMessage = "Jar is not running in " + peerid; + } + } + if (sanityCheckErrorFlag) { + if (portCheckAndKill(port)) { + FunctionsLogger.debug("Ports are available for transcations in " + peerid); + FunctionsLogger.debug("Ports check true"); + } else { + sanityCheckErrorFlag = false; + FunctionsLogger.debug("Ports are not available for " + peerid); + FunctionsLogger.debug("Ports check false"); + sanityMessage = "Ports are not available for " + peerid; + } + } + + return sanityCheckErrorFlag; + } + + public static boolean checkIPFSStatus(String peerid, IPFS ipfs) { + FunctionsLogger.info("Entering checkIPFSStatus"); + boolean swarmConnectedStatus = false; + try { + MultiAddress multiAddress = new MultiAddress("/ipfs/" + peerid); + FunctionsLogger.info("MultiAdrress concated " + multiAddress + "|||"); + boolean output = swarmConnectP2P(peerid, ipfs); + + if (output) { + swarmConnectedStatus = true; + FunctionsLogger.debug("Swarm is already connected"); + } else { + swarmConnectedStatus = false; + FunctionsLogger.debug("Swarm is not connected"); + } + } catch (Exception e) { + FunctionsLogger.error("Check Swarm Connect is failed", e); + + } + FunctionsLogger.info("checkIPFSStatus return value is " + swarmConnectedStatus); + return swarmConnectedStatus; + } + + public static boolean ping(String peerid, int port) throws IOException, JSONException { + JSONObject pingCheck = PingCheck.Ping(peerid, port); + if (pingCheck.getString("status").contains("Failed")) { + return false; + } else + return true; + + } + + // public static String getPing(int port) { + // try { + // + // String didContent = readFile(DATA_PATH + "DID.json"); + // JSONArray didArray = new JSONArray(didContent); + // String myPeerID = didArray.getJSONObject(0).getString("peerid"); + // + // listen(myPeerID.concat("Ping"), port); + // ServerSocket ss = new ServerSocket(port); + // FunctionsLogger.info("Get Ping Listening on port " + port + " appname " + + // myPeerID.concat("Ping")); + // Socket socket = ss.accept(); + // BufferedReader input = new BufferedReader(new + // InputStreamReader(socket.getInputStream())); + // PrintStream output = new PrintStream(socket.getOutputStream()); + // FunctionsLogger.info("getPing- waiting response from server"); + // String peerID = input.readLine(); + // if (peerID != null && peerID.contains("Qm")) { + // FunctionsLogger.info("getPing - Received message from server"); + // output.println("Ping received"); + // FunctionsLogger.debug("Ping received from sender"); + // + // output.close(); + // input.close(); + // socket.close(); + // ss.close(); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + // FunctionsLogger.info("If - Closing Sockets"); + // return "Ping received from sender and Pong sent"; + // } + // else{ + // output.close(); + // input.close(); + // socket.close(); + // ss.close(); + // FunctionsLogger.info("Else - Closing Sockets"); + // return "Ping received from sender but not PeerID"; + // } + // + // } catch (Exception e) { + // FunctionsLogger.error("Error in client side communication", e); + // return "Error in client side communication"; + // } + // } + + public static boolean bootstrapConnect(String peerid, IPFS ipfs) { + FunctionsLogger.info("bootstrapConnect- entering function"); + String bootNode; + boolean bootstrapConnected = false; + + MultiAddress multiAddress = new MultiAddress("/ipfs/" + peerid); + FunctionsLogger.info("bootstrapConnect- multiaddress is " + multiAddress.toString()); + + String output = swarmConnectProcess(multiAddress); + try { + for (int i = 0; i < BOOTSTRAPS.length(); i++) { + FunctionsLogger.info("bootstrapConnect- Bootstrap length is " + BOOTSTRAPS.length()); + + if (!bootstrapConnected) { + FunctionsLogger.info("bootstrapConnect- Connecting to bootstrp " + i); + bootNode = String.valueOf(BOOTSTRAPS.get(i)); + bootNode = bootNode.substring(bootNode.length() - 46); + FunctionsLogger.info("bootstrapConnect- trying to connect with " + bootNode); + + multiAddress = new MultiAddress("/ipfs/" + bootNode); + output = swarmConnectProcess(multiAddress); + FunctionsLogger.info("bootstrapConnect- connection status to " + bootNode + " is " + output); + if (output.contains("success")) { + FunctionsLogger.info("bootstrapConnect- trying to swarm connect"); + multiAddress = new MultiAddress("/ipfs/" + bootNode + "/p2p-circuit/ipfs/" + peerid); + output = swarmConnectProcess(multiAddress); + FunctionsLogger.info("bootstrapConnect- Swarmconnect status is " + output); + if (!output.contains("success")) { + IPFSNetworkLogger.debug("swarm attempt failed with " + peerid); + } else { + IPFSNetworkLogger.debug("swarm Connected : " + peerid); + bootstrapConnected = true; + } + } else { + IPFSNetworkLogger.debug("bootstrap connection failed! " + bootNode); + } + + } + } + + } catch (Exception e) { + FunctionsLogger.error("Error occured during IPFS Swarm connect with bootstrap", e); + + } + + if (bootstrapConnected) { + return true; + } else { + return false; + } + + } + + public static boolean portCheckAndKill(int port) { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + boolean portStatus = false; + + try { + if (getOsName() != "Windows") { + portStatus = releasePorts(port); + } else { + portStatusWindows(port); + portStatus = portStatusWindows(port); + } + } catch (Exception e) { + FunctionsLogger.error("Error occured during port checking ", e); + } + return portStatus; + + } + + /** + * This function will release the port in linux based machines if the port is + * already in use + */ + public static boolean releasePorts(int port) { + FunctionsLogger.info("releasePorts- "); + boolean releasedPort = false; + String processStr; + Process processId; + try { + processId = Runtime.getRuntime().exec("lsof -ti :" + port); + long currentPid = ProcessHandle.current().pid(); + BufferedReader br = new BufferedReader( + new InputStreamReader(processId.getInputStream())); + FunctionsLogger.info("releasePorts- process " + br.readLine() + " is occupied in " + port); + processId = Runtime.getRuntime().exec("pgrep ipfs"); + BufferedReader ipfsPidBr = new BufferedReader(new InputStreamReader(processId.getInputStream())); + + processStr = br.readLine(); + FunctionsLogger.info("releasePorts- Process string is " + processStr); + if (processStr != null) { + FunctionsLogger.info("releasePorts- Processstr is not null"); + if (String.valueOf(currentPid) != processStr && ipfsPidBr.readLine() != processStr) { + FunctionsLogger.info("releasePorts- jar is running on " + currentPid + " and IPFS is occupied in " + + ipfsPidBr.readLine()); + FunctionsLogger.debug("Port " + port + " is in using, killing PID " + processStr); + processId = Runtime.getRuntime().exec("kill -9 " + processStr); + FunctionsLogger.info("releasePorts- killing " + processStr); + + } + } + releasedPort = true; + FunctionsLogger.info("releasePorts- status is " + releasedPort); + processId.waitFor(); + FunctionsLogger.info("releasePorts- Waitng for process"); + processId.destroy(); + FunctionsLogger.info("releasePorts- destorying process after waiting"); + } catch (Exception e) { + FunctionsLogger.error("Exception Occured at releasePort", e); + e.printStackTrace(); + } + return releasedPort; + } + + public static boolean portStatusWindows(int port) { + FunctionsLogger.info("Starting portStatusWindows"); + boolean releasedPort = false; + String processStr; + Process p; + try { + Runtime rt = Runtime.getRuntime(); + Process proc = rt.exec("cmd /c netstat -ano | findstr " + port); + FunctionsLogger.info("Checking port status"); + long currentPid = ProcessHandle.current().pid(); + BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); + processStr = stdInput.readLine(); + FunctionsLogger.info("Process id found for port is " + processStr + " current jar pid is " + currentPid); + if (processStr != null && String.valueOf(currentPid) != processStr) { + int index = processStr.lastIndexOf(" "); + String sc = processStr.substring(index, processStr.length()); + // System.out.println("Port "+port+" is locked by PID "+sc+". Kindly close this + // port and retry transcation"); + if (sc != String.valueOf(currentPid)) { + FunctionsLogger.debug("Port " + port + " is locked by PID " + sc); + } else { + FunctionsLogger.debug("Port " + port + " is locked by current jar with PID " + sc); + } + } else { + releasedPort = true; + FunctionsLogger.info("Port is unlocked"); + } + } catch (Exception e) { + FunctionsLogger.error("Exception occured at portStatusWindows", e); + e.printStackTrace(); + } + return releasedPort; + } + } diff --git a/src/com/rubix/Resources/IPFSNetwork.java b/src/com/rubix/Resources/IPFSNetwork.java index fc877518..5cc6917c 100644 --- a/src/com/rubix/Resources/IPFSNetwork.java +++ b/src/com/rubix/Resources/IPFSNetwork.java @@ -572,7 +572,7 @@ public static void executeIPFSCommands(String command) { } } - public static void swarmConnectP2P(String peerid, IPFS ipfs) throws JSONException { + public static boolean swarmConnectP2P(String peerid, IPFS ipfs) throws JSONException { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String bootNode; boolean swarmConnected = false; @@ -597,17 +597,22 @@ public static void swarmConnectP2P(String peerid, IPFS ipfs) throws JSONExceptio output = swarmConnectProcess(multiAddress); if (!output.contains("success")) { IPFSNetworkLogger.debug("swarm attempt failed with " + peerid); + swarmConnected = false; } else { IPFSNetworkLogger.debug("swarm Connected : " + peerid); swarmConnected = true; } } else { IPFSNetworkLogger.debug("bootstrap connection failed! " + bootNode); + swarmConnected = false; } } } + } else { + swarmConnected = true; } + return swarmConnected; } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index e2d9a8d2..3218e0ea 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -14,17 +14,19 @@ import static com.rubix.Resources.Functions.formatAmount; import static com.rubix.Resources.Functions.getCurrentUtcTime; 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.pathSet; +import static com.rubix.Resources.Functions.randomPositions; import static com.rubix.Resources.Functions.readFile; +import static com.rubix.Resources.Functions.strToIntArray; import static com.rubix.Resources.Functions.syncDataTable; import static com.rubix.Resources.Functions.updateJSON; import static com.rubix.Resources.Functions.writeToFile; import static com.rubix.Resources.IPFSNetwork.add; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.get; -import static com.rubix.Resources.IPFSNetwork.getMineID; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.pin; import static com.rubix.Resources.IPFSNetwork.repo; @@ -109,6 +111,7 @@ public static String receive() { TokenReceiverLogger.debug("Receiver Listening on " + RECEIVER_PORT + " appname " + receiverPeerID); sk = ss.accept(); + TokenReceiverLogger.debug("Data Incoming..."); BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintStream output = new PrintStream(sk.getOutputStream()); long startTime = System.currentTimeMillis(); @@ -129,8 +132,7 @@ public static String receive() { return APIResponse.toString(); } - syncDataTable(null, senderPeerID); - + TokenReceiverLogger.debug("Data Received: " + senderPeerID); swarmConnectP2P(senderPeerID, ipfs); String senderDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", senderPeerID); @@ -206,16 +208,13 @@ public static String receive() { JSONArray doubleSpentToken = new JSONArray(); JSONArray stakedToken = new JSONArray(); boolean tokenOwners = true; - boolean validTxnSignatures = true; boolean incompleteStake = false; ArrayList ownersArray = new ArrayList(); - ArrayList stakeOwnersArray = new ArrayList(); ArrayList previousSender = new ArrayList(); JSONArray ownersReceived = new JSONArray(); for (int i = 0; i < wholeTokens.length(); ++i) { try { - TokenReceiverLogger.debug("Checking owners and credits / signatures for " + wholeTokens.getString(i) - + " Please wait..."); + TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + " Please wait..."); ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); if (ownersArray.size() > 2) { @@ -236,85 +235,32 @@ public static String receive() { tokenOwners = false; } } - - // ! to avoid fraud multiple pinning of tokens (fork) - // ! check sender has signatures and credits to back the token transfer even if - // ! someone has pinned the token - // ! check if sender has provided credits to quorum for this transfer - // validTxnSignatures = false; - - } catch (IOException e) { - - TokenReceiverLogger.trace("Ipfs dht find did not execute (double spend check)"); - } - - // ! starts mine ID check - - try { - - // ! STEP 1 : checking if any of the tokens are actively staked for mining - - TokenReceiverLogger.debug("Checking mine ID for " + wholeTokens.getString(i) + " Please wait..."); - String mineID = getMineID(wholeTokens.getString(i).toString(), ipfs); - stakeOwnersArray = IPFSNetwork.dhtOwnerCheck(mineID); - - if (stakeOwnersArray.size() > 0) { - - // ! check sign on pinned mine ID - - // JSONArray stakedTC = wholeTokenChains.getJSONArray(i); - // JSONObject stakeInfo = stakedTC.getJSONObject(1); - - // String minedToken = stakeInfo.getString(MINED_RBT); - - // TokenReceiverLogger - // .debug("Checking owners and credits / signatures for mined token: " + - // minedToken - // + " Please wait..."); - - // String minedTC = get(minedToken, ipfs); - - // JSONArray minedTCArray = new JSONArray(minedTC); - - // if (minedTCArray.length() < 32) { - // incompleteStake = true; - // } - - // TokenReceiverLogger.trace("Failed to fetch mined token chain"); - - } - - // ! STEP 2 : checking if any of the tokens are newly minted to verify stake - } catch (IOException e) { - TokenReceiverLogger.trace("Ipfs dht find did not execute (mineID check)"); + TokenReceiverLogger.debug("Ipfs dht find did not execute"); } } - - if (!tokenOwners) { - // JSONArray owners = new JSONArray(); - // for (int i = 0; i < ownersArray.size(); i++) - // owners.put(ownersArray.get(i).toString()); - // TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); - // TokenReceiverLogger.debug("Owners: " + owners); - // output.println("420"); - // output.println(doubleSpentToken.toString()); - // output.println(owners.toString()); - // APIResponse.put("did", senderDidIpfsHash); - // APIResponse.put("tid", "null"); - // APIResponse.put("status", "Failed"); - // APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + - // owners); - // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - // output.close(); - // input.close(); - // sk.close(); - // ss.close(); - // return APIResponse.toString(); - - TokenReceiverLogger.debug("Multiple Pins for " + doubleSpentToken); - } + // if (!tokenOwners) { + // JSONArray owners = new JSONArray(); + // for (int i = 0; i < ownersArray.size(); i++) + // owners.put(ownersArray.get(i).toString()); + // TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); + // TokenReceiverLogger.debug("Owners: " + owners); + // output.println("420"); + // output.println(doubleSpentToken.toString()); + // output.println(owners.toString()); + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", "null"); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + + // owners); + // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + // output.close(); + // input.close(); + // sk.close(); + // ss.close(); + // return APIResponse.toString(); + // } if (incompleteStake) { TokenReceiverLogger.debug("Token Height not reached for corresponding Staked Tokens " + stakedToken); @@ -333,28 +279,26 @@ public static String receive() { return APIResponse.toString(); } - // ! ends mineID checks - String senderToken = TokenDetails.toString(); String consensusID = calculateHash(senderToken, "SHA3-256"); writeToFile(LOGGER_PATH + "consensusID", consensusID, false); String consensusIDIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "consensusID", ipfs); deleteFile(LOGGER_PATH + "consensusID"); - if (!IPFSNetwork.dhtEmpty(consensusIDIPFSHash, ipfs)) { - TokenReceiverLogger.debug("consensus ID not unique" + consensusIDIPFSHash); - output.println("421"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Consensus ID not unique"); - IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } + // if (!IPFSNetwork.dhtEmpty(consensusIDIPFSHash, ipfs)) { + // TokenReceiverLogger.debug("consensus ID not unique" + consensusIDIPFSHash); + // output.println("421"); + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", "null"); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Consensus ID not unique"); + // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + // output.close(); + // input.close(); + // sk.close(); + // ss.close(); + // return APIResponse.toString(); + // } // Check IPFS get for all Tokens int ipfsGetFlag = 0; @@ -435,9 +379,7 @@ public static String receive() { } } } - if (!chainFlag) { - String errorMessage = "Broken Cheque Chain"; output.println("423"); APIResponse.put("did", senderDidIpfsHash); @@ -482,6 +424,8 @@ public static String receive() { } } + String ownerIdentityHash; + JSONArray allTokens = new JSONArray(); if (!partsAvailable) { String errorMessage = "Token wholly spent already"; output.println("424"); @@ -496,8 +440,27 @@ public static String receive() { sk.close(); ss.close(); return APIResponse.toString(); - } else - output.println("200"); + } else { + // Calculate Token Ownership + for (int i = 0; i < wholeTokens.length(); i++) + allTokens.put(wholeTokens.getString(i)); + for (int i = 0; i < partTokens.length(); i++) + allTokens.put(partTokens.getString(i)); + + String tokens = allTokens.toString(); + String hashString = tokens.concat(receiverDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + + String positions = getSignFromShares(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"), + hashForPositions); + + String ownerIdentity = receiverDidIpfsHash.concat(positions); + ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); + + output.println(ownerIdentityHash); + + } + // output.println("200"); String senderDetails; try { @@ -522,6 +485,15 @@ public static String receive() { String comment = SenderDetails.getString("comment"); String Status = SenderDetails.getString("status"); String QuorumDetails = SenderDetails.getString("quorumsign"); + String ownerSigns = SenderDetails.getString("ownerSigns"); + + String hashForOwners = calculateHash(ownerSigns, "SHA3-256"); + BufferedImage pvt = ImageIO.read(new File(DATA_PATH.concat(receiverPeerID).concat("PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(pvt); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + JSONObject positions = randomPositions("signer", hashForOwners, 32, privateIntegerArray1); + + String ownerIdentity = receiverDidIpfsHash.concat(positions.toString()); BufferedImage senderWidImage = ImageIO.read(new File(DATA_PATH + senderDidIpfsHash + "/PublicShare.png")); SenWalletBin = PropImage.img2bin(senderWidImage); @@ -672,12 +644,6 @@ public static String receive() { groupTokens.add(wholeTokens.getString(k)); } - // ! calculating owner hash for each token - - String privatePicker = calculateHash(wholeTokens.getString(i).concat(receiverDidIpfsHash), - "SHA3-256"); - // String privatePoistions = - JSONArray arrToken = new JSONArray(); JSONObject objectToken = new JSONObject(); objectToken.put("tokenHash", wholeTokens.getString(i)); @@ -689,8 +655,7 @@ public static String receive() { obj2.put("group", groupTokens); obj2.put("comment", comment); obj2.put("tid", tid); - // ! add current owner hash here.. - // obj2.put("currentOwner", senderDidIpfsHash); + obj2.put("owner", ownerIdentity); arr1.put(obj2); writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); } @@ -716,6 +681,7 @@ public static String receive() { newPartObject.put("comment", comment); newPartObject.put("tid", tid); newPartObject.put("nextHash", ""); + newPartObject.put("owner", ownerIdentity); if (partTokenChainContent.getJSONArray(i).length() == 0) newPartObject.put("previousHash", ""); else @@ -750,7 +716,7 @@ public static String receive() { JSONObject transactionRecord = new JSONObject(); transactionRecord.put("role", "Receiver"); - transactionRecord.put("tokens", wholeTokens); + transactionRecord.put("tokens", allTokens); transactionRecord.put("txn", tid); transactionRecord.put("quorumList", quorumSignatures.keys()); transactionRecord.put("senderDID", senderDidIpfsHash); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 75cf0d49..109d11cd 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -11,6 +11,8 @@ 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.correctPartToken; +import static com.rubix.Resources.Functions.correctToken; import static com.rubix.Resources.Functions.deleteFile; import static com.rubix.Resources.Functions.formatAmount; import static com.rubix.Resources.Functions.getCurrentUtcTime; @@ -22,7 +24,8 @@ import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.Functions.partTokenBalance; import static com.rubix.Resources.Functions.readFile; -import static com.rubix.Resources.Functions.removeToken; +import static com.rubix.Resources.Functions.sanityCheck; +import static com.rubix.Resources.Functions.sanityMessage; import static com.rubix.Resources.Functions.syncDataTable; import static com.rubix.Resources.Functions.updateJSON; import static com.rubix.Resources.Functions.updateQuorum; @@ -92,20 +95,31 @@ 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 receiverPeerId = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", receiverDidIpfsHash); String pvt = detailsObject.getString("pvt"); double requestedAmount = detailsObject.getDouble("amount"); int type = detailsObject.getInt("type"); String comment = detailsObject.getString("comment"); APIResponse = new JSONObject(); + int intPart = (int) requestedAmount, wholeAmount; String senderPeerID = getPeerID(DATA_PATH + "DID.json"); TokenSenderLogger.debug("sender peer id" + senderPeerID); String senderDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", senderPeerID); TokenSenderLogger.debug("sender did ipfs hash" + senderDidIpfsHash); + boolean sanityCheck = sanityCheck(receiverPeerId, ipfs, port + 10); + if (!sanityCheck) { + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", sanityMessage); + TokenSenderLogger.warn(sanityMessage); + return APIResponse; + } + if (senderMutex) { APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); @@ -131,7 +145,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception writeToFile(partTokensFile.toString(), "[]", false); } - int intPart = (int) requestedAmount, wholeAmount; TokenSenderLogger.debug("Requested Part: " + requestedAmount); TokenSenderLogger.debug("Int Part: " + intPart); String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); @@ -330,7 +343,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception TokenSenderLogger.debug("Sender by Receiver Hash " + authSenderByRecHash); TokenSenderLogger.debug("TID on sender " + tid); - JSONArray quorumArray; + JSONArray allTokens = new JSONArray(); + for (int i = 0; i < wholeTokens.length(); i++) + allTokens.put(wholeTokens.getString(i)); + for (int i = 0; i < partTokens.length(); i++) + allTokens.put(partTokens.getString(i)); + JSONArray alphaQuorum = new JSONArray(); JSONArray betaQuorum = new JSONArray(); JSONArray gammaQuorum = new JSONArray(); @@ -340,7 +358,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception ArrayList betaPeersList; ArrayList gammaPeersList; - long startTime = System.currentTimeMillis(); + JSONArray quorumArray; switch (type) { case 1: { writeToFile(LOGGER_PATH + "tempbeta", tid.concat(senderDidIpfsHash), false); @@ -352,7 +370,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception deleteFile(LOGGER_PATH + "tempgamma"); quorumArray = getQuorum(betaHash, gammaHash, senderDidIpfsHash, receiverDidIpfsHash, - wholeTokens.length()); + allTokens.length()); break; } @@ -373,18 +391,37 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } - TokenSenderLogger.debug("1"); - TokenSenderLogger.debug("Whole tokens: " + wholeTokens); - TokenSenderLogger.debug("Part tokens: " + partTokens); - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - eventLogger.debug("Get Quorum List " + totalTime); + int alphaCheck = 0, betaCheck = 0, gammaCheck = 0; + JSONArray sanityFailedQuorum = new JSONArray(); + for (int i = 0; i < quorumArray.length(); i++) { + String quorumPeerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", + quorumArray.getString(i)); + boolean quorumSanityCheck = sanityCheck(quorumPeerID, ipfs, port + 11); + + if (!quorumSanityCheck) { + sanityFailedQuorum.put(quorumPeerID); + if (i <= 6) + alphaCheck++; + if (i >= 7 && i <= 13) + betaCheck++; + if (i >= 14 && i <= 20) + gammaCheck++; + } + } + + if (alphaCheck > 2 || betaCheck > 2 || gammaCheck > 2) { + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + String message = "Quorum: ".concat(sanityFailedQuorum.toString()).concat(" "); + APIResponse.put("message", message.concat(sanityMessage)); + TokenSenderLogger.warn("Quorum: ".concat(message.concat(sanityMessage))); + return APIResponse; + } + + long startTime, endTime, totalTime; - startTime = System.currentTimeMillis(); QuorumSwarmConnect(quorumArray, ipfs); - endTime = System.currentTimeMillis(); - totalTime = endTime - startTime; - eventLogger.debug("Swarm Connect " + totalTime); alphaSize = quorumArray.length() - 14; @@ -417,7 +454,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } syncDataTable(receiverDidIpfsHash, null); - receiverPeerId = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", receiverDidIpfsHash); + // receiverPeerId = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", + // receiverDidIpfsHash); if (!receiverPeerId.equals("")) { TokenSenderLogger.debug("Swarm connecting to " + receiverPeerId); @@ -545,7 +583,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String doubleSpend = calculateHash(doubleSpendString, "SHA3-256"); writeToFile(LOGGER_PATH + "doubleSpend", doubleSpend, false); - TokenSenderLogger.debug("********Double Spend Hash********* : " + doubleSpend); + TokenSenderLogger.debug("********Double Spend Hash*********: " + doubleSpend); IPFSNetwork.addHashOnly(LOGGER_PATH + "doubleSpend", ipfs); deleteFile(LOGGER_PATH + "doubleSpend"); @@ -579,37 +617,42 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } - if (tokenAuth != null && (!tokenAuth.equals("200"))) { + if (tokenAuth != null && (!tokenAuth.startsWith("4"))) { switch (tokenAuth) { case "420": String doubleSpent = input.readLine(); String owners = input.readLine(); JSONArray ownersArray = new JSONArray(owners); + correctToken(); TokenSenderLogger.info("Multiple Owners for " + doubleSpent); - APIResponse.put("message", "Multiple Owners for " + doubleSpent); - APIResponse.put("Owners", ownersArray); - removeToken(); + TokenSenderLogger.info("Owners " + ownersArray); + TokenSenderLogger.info("Kindly re-initiate transaction"); + APIResponse.put("message", "Multiple Owners for " + doubleSpent + " Owners: " + ownersArray + + ". Kindly re-initiate transaction"); break; case "421": - TokenSenderLogger.info("Consensus ID not unique"); - APIResponse.put("message", "Consensus ID not unique"); - removeToken(); + correctToken(); + TokenSenderLogger.info("Consensus ID not unique. Kindly re-initiate transaction"); + APIResponse.put("message", "Consensus ID not unique. Kindly re-initiate transaction"); break; case "422": - TokenSenderLogger.info("Tokens Not Verified"); - APIResponse.put("message", "Tokens Not Verified"); - removeToken(); + correctToken(); + TokenSenderLogger.info("Tokens Not Verified. Kindly re-initiate transaction"); + APIResponse.put("message", "Tokens Not Verified. Kindly re-initiate transaction"); break; case "423": - TokenSenderLogger.info("Broken Cheque Chain"); - APIResponse.put("message", "Broken Cheque Chain"); + correctPartToken(); + TokenSenderLogger.info("Broken Cheque Chain. Kindly re-initiate transaction"); + APIResponse.put("message", "Broken Cheque Chain. Kindly re-initiate transaction"); break; case "424": - TokenSenderLogger.info("Token wholly spent already"); - APIResponse.put("message", "Token wholly spent already"); + correctPartToken(); + TokenSenderLogger.info("Token wholly spent already. Kindly re-initiate transaction"); + APIResponse.put("message", "Token wholly spent already. Kindly re-initiate transaction"); break; case "425": + correctToken(); TokenSenderLogger.info("Stake incomplete for a selected token"); APIResponse.put("message", "Stake incomplete for a selected token"); break; @@ -634,6 +677,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception dataObject.put("message", doubleSpendString); dataObject.put("receiverDidIpfs", receiverDidIpfsHash); dataObject.put("pvt", pvt); + dataObject.put("ownerIdentity", tokenAuth); dataObject.put("senderDidIpfs", senderDidIpfsHash); dataObject.put("token", wholeTokens.toString()); dataObject.put("alphaList", alphaPeersList); @@ -661,9 +705,11 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } + JSONArray ownerSigns = InitiatorConsensus.ownerSigns; TokenSenderLogger.debug("Consensus Reached"); senderDetails2Receiver.put("status", "Consensus Reached"); senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); + senderDetails2Receiver.put("ownerSigns", ownerSigns.toString()); output.println(senderDetails2Receiver); TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); @@ -801,17 +847,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception updateQuorum(quorumArray, signedQuorumList, true, type); - JSONArray allTokens = new JSONArray(); - for (int i = 0; i < wholeTokens.length(); i++) - allTokens.put(wholeTokens.getString(i)); - for (int i = 0; i < partTokens.length(); i++) - allTokens.put(partTokens.getString(i)); - - TokenSenderLogger.debug("4"); - TokenSenderLogger.debug("All tokens: " + allTokens); - TokenSenderLogger.debug("Whole tokens: " + wholeTokens); - TokenSenderLogger.debug("Part tokens: " + partTokens); - JSONObject transactionRecord = new JSONObject(); transactionRecord.put("role", "Sender"); transactionRecord.put("tokens", allTokens); From b64a70cfd9e60b77526892cbe39945a3151c2e0b Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 3 Mar 2022 18:56:39 +0530 Subject: [PATCH 013/179] fix staking quorum picking Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 253 +++++++++--------- src/com/rubix/Consensus/QuorumConsensus.java | 6 +- src/com/rubix/Constants/MiningConstants.java | 2 +- 3 files changed, 137 insertions(+), 124 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 39dabe78..10b47b1f 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -4,7 +4,7 @@ import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; import static com.rubix.Constants.MiningConstants.MINE_ID; import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; -import static com.rubix.Constants.MiningConstants.MINING_TID; +import static com.rubix.Constants.MiningConstants.MINE_TID; import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; @@ -62,6 +62,8 @@ public class InitiatorConsensus { public static volatile int[] quorumResponse = { 0, 0, 0 }; public static volatile boolean stakeComplete = false; public static volatile JSONArray finalQuorumSignsArray = new JSONArray(); + public static JSONArray ownerSigns = new JSONArray(); + private static int levelHeightValue; /** * Added by Anuradha K on 04/01/20222. @@ -157,7 +159,7 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri PrintStream[] qOut = new PrintStream[QUORUM_COUNT]; BufferedReader[] qIn = new BufferedReader[QUORUM_COUNT]; String[] quorumID = new String[QUORUM_COUNT]; - String[] signedAlphaQuorumID = new String[minQuorum(7)]; + String[] signedAlphaQuorumPID = new String[7]; PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); JSONObject dataObject = new JSONObject(data); String hash = dataObject.getString("hash"); @@ -356,6 +358,11 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri InitiatorConsensusLogger.debug(role + " node authenticated at index " + index); boolean voteStatus = voteNCount(index, quorumSize); if (quorumResponse[index] <= minQuorum(quorumSize) && voteStatus) { + + if (j <= 7) { + signedAlphaQuorumPID[j] = quorumID[j]; + } + InitiatorConsensusLogger .debug("waiting for " + quorumSize + " +signs " + role); while (quorumResponse[index] < minQuorum(quorumSize)) { @@ -399,154 +406,160 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (operation.equals("new-credits-mining")) { - Thread[] stakingThreads = new Thread[signedAlphaQuorumID.length]; + levelHeightValue = levelHeight(); + + Thread[] stakingThreads = new Thread[signedAlphaQuorumPID.length]; // choosing a quorum member from 1 to 5 who have signed the transaction - for (int p = 0; p < signedAlphaQuorumID.length; p++) { + for (int p = 0; p < signedAlphaQuorumPID.length; p++) { int s = p; stakingThreads[p] = new Thread(() -> { try { - InitiatorConsensusLogger.debug( - "Contacting Signed Alpha Quorum ID : " + signedAlphaQuorumID[s] - + " for staking. Index: " + s); - - qSocket[s] = new Socket("127.0.0.1", PORT + s); - qSocket[s].setSoTimeout(socketTimeOut); - qIn[s] = new BufferedReader(new InputStreamReader(qSocket[s].getInputStream())); - qOut[s] = new PrintStream(qSocket[s].getOutputStream()); - - qOut[s].println("stake-token"); - try { - - qResponse[s] = qIn[s].readLine(); - // convert to JSON array - JSONArray stakingTokenDetals = new JSONArray(qResponse[s]); - // get token chain and token ID from the array - String stakingTokenHash = stakingTokenDetals.getString(0); - JSONArray stakingTokenChain = stakingTokenDetals.getJSONArray(1); - - String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", - "peerid", signedAlphaQuorumID[s]); - if (checkTokenOwnershiByDID(stakingTokenHash, stakingQuorumDID) - && stakingTokenChain.length() > levelHeight()) { - - InitiatorConsensusLogger.debug("Staking Token Received and Verified from " - + signedAlphaQuorumID[s] + " " + qResponse[s]); - - String mineID = getMineID(stakingTokenHash, ipfs); - InitiatorConsensusLogger - .debug("Sending mine ID to miner :" + mineID); - JSONObject detToSign = new JSONObject(); - detToSign.put(MINE_ID, stakingTokenHash); - detToSign.put(MINING_TID, stakingQuorumDID); - detToSign.put(MINED_RBT, stakingTokenHash); - qOut[s].println(detToSign.toString()); - - JSONObject stakingQuorumSigned = new JSONObject(); - - try { - qResponse[s] = qIn[s].readLine(); - // convert to JSON array - stakingQuorumSigned = new JSONObject(qResponse[s]); - InitiatorConsensusLogger.debug("Signature for Mining ID Received from " - + signedAlphaQuorumID[s] + " " + qResponse[s]); - } catch (SocketException e) { + if (signedAlphaQuorumPID[s] != null) { + InitiatorConsensusLogger.debug( + "Contacting Signed Alpha Quorum Peer : " + signedAlphaQuorumPID[s] + + " for staking. Index: " + s); + + qSocket[s] = new Socket("127.0.0.1", PORT + s); + qSocket[s].setSoTimeout(socketTimeOut); + qIn[s] = new BufferedReader(new InputStreamReader(qSocket[s].getInputStream())); + qOut[s] = new PrintStream(qSocket[s].getOutputStream()); + + qOut[s].println("stake-token"); + try { + + qResponse[s] = qIn[s].readLine(); + // convert to JSON array + JSONArray stakingTokenDetals = new JSONArray(qResponse[s]); + // get token chain and token ID from the array + String stakingTokenHash = stakingTokenDetals.getString(0); + JSONArray stakingTokenChain = stakingTokenDetals.getJSONArray(1); + + String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", + "peerid", signedAlphaQuorumPID[s]); + if (checkTokenOwnershiByDID(stakingTokenHash, stakingQuorumDID) + && stakingTokenChain.length() > levelHeightValue) { + + InitiatorConsensusLogger.debug("Staking Token Received and Verified from " + + signedAlphaQuorumPID[s] + " " + qResponse[s]); + + String mineID = getMineID(stakingTokenHash, ipfs); InitiatorConsensusLogger - .warn("Quorum " + quorumID[s] + " is unable to Respond!"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); - } + .debug("Sending mine ID to miner :" + mineID); + JSONObject detToSign = new JSONObject(); + detToSign.put(MINE_ID, mineID); + detToSign.put(MINE_TID, detailsToken.getString("Tid")); + detToSign.put(MINED_RBT, detailsToken.getString("token")); + qOut[s].println(detToSign.toString()); + + JSONObject stakingQuorumSigned = new JSONObject(); + + try { + qResponse[s] = qIn[s].readLine(); + // convert to JSON array + stakingQuorumSigned = new JSONObject(qResponse[s]); + InitiatorConsensusLogger.debug("Signature for Mining ID Received from " + + signedAlphaQuorumPID[s] + " " + qResponse[s]); + } catch (SocketException e) { + InitiatorConsensusLogger + .warn("Quorum " + quorumID[s] + " is unable to Respond!"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); + } - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakingQuorumDID); - detailsToVerify.put("hash", mineID); - detailsToVerify.put("signature", stakingQuorumSigned.getString(MINE_ID_SIGN)); + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakingQuorumDID); + detailsToVerify.put("hash", mineID); + detailsToVerify.put("signature", stakingQuorumSigned.getString(MINE_ID_SIGN)); + + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + stakingSignature.put(MINE_TID, detailsToken.getString("Tid")); + stakingSignature.put(MINED_RBT, detailsToken.getString("token")); + stakingSignature.put(MINE_ID, mineID); + stakingSignature.put(STAKED_QUORUM_DID, stakingQuorumDID); + stakingSignature.put(STAKED_TOKEN, stakingTokenHash); + + stakingSignature.put(STAKED_TOKEN_SIGN, stakingQuorumSigned.getString( + STAKED_TOKEN_SIGN)); + stakingSignature.put(MINING_TID_SIGN, stakingQuorumSigned.getString( + MINING_TID_SIGN)); + stakingSignature.put(MINED_RBT_SIGN, stakingQuorumSigned.getString( + MINED_RBT_SIGN)); + stakingSignature.put(MINE_ID_SIGN, + stakingQuorumSigned.getString(MINE_ID_SIGN)); + + if (!stakeComplete) { + FileWriter shareWriter = new FileWriter( + new File(LOGGER_PATH + "mineID.txt"), + true); + shareWriter.write(detailsToVerify.toString(0)); + shareWriter.close(); + File readMineID = new File(LOGGER_PATH + "mineID.txt"); + String mineData = add(readMineID.toString(), ipfs); + pin(mineData, ipfs); + + File mineIDFile = new File( + WALLET_DATA_PATH.concat("/Stakes/").concat(mineData) + .concat(".json")); + if (!mineIDFile.exists()) + mineIDFile.createNewFile(); + writeToFile(mineIDFile.toString(), qResponse[s], false); + + InitiatorConsensusLogger.debug("Mine object: " + mineData); + deleteFile(LOGGER_PATH + "mineID.txt"); + + InitiatorConsensusLogger.debug("Staking Successful at index " + s); - if (Authenticate.verifySignature(detailsToVerify.toString())) { + IPFSNetwork + .executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); - stakingSignature.put(MINING_TID, detailsToken.getString("Tid")); - stakingSignature.put(MINED_RBT, detailsToken.getString("token")); - stakingSignature.put(MINE_ID, mineID); - stakingSignature.put(STAKED_QUORUM_DID, stakingQuorumDID); - stakingSignature.put(STAKED_TOKEN, stakingTokenHash); - - stakingSignature.put(STAKED_TOKEN_SIGN, stakingQuorumSigned.getString( - STAKED_TOKEN_SIGN)); - stakingSignature.put(MINING_TID_SIGN, stakingQuorumSigned.getString( - MINING_TID_SIGN)); - stakingSignature.put(MINED_RBT_SIGN, stakingQuorumSigned.getString( - MINED_RBT_SIGN)); - stakingSignature.put(MINE_ID_SIGN, stakingQuorumSigned.getString(MINE_ID_SIGN)); - - if (!stakeComplete) { - FileWriter shareWriter = new FileWriter( - new File(LOGGER_PATH + "mineID.txt"), - true); - shareWriter.write(detailsToVerify.toString(0)); - shareWriter.close(); - File readMineID = new File(LOGGER_PATH + "mineID.txt"); - String mineData = add(readMineID.toString(), ipfs); - pin(mineData, ipfs); - - File mineIDFile = new File( - WALLET_DATA_PATH.concat("/Stakes/").concat(mineData) - .concat(".json")); - if (!mineIDFile.exists()) - mineIDFile.createNewFile(); - writeToFile(mineIDFile.toString(), qResponse[s], false); - - InitiatorConsensusLogger.debug("Mine object: " + mineData); - deleteFile(LOGGER_PATH + "mineID.txt"); - - InitiatorConsensusLogger.debug("Staking Successful at index " + s); + JSONObject stakingInfo = new JSONObject(); + stakingInfo.put("StakerDID", stakingQuorumDID); + stakingInfo.put("StakedokenID", stakingTokenHash); + stakingInfo.put("minedToken", detailsToken); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); + JSONArray creditArray = new JSONArray(); - JSONObject stakingInfo = new JSONObject(); - stakingInfo.put("StakerDID", stakingQuorumDID); - stakingInfo.put("StakedokenID", stakingTokenHash); - stakingInfo.put("minedToken", detailsToken); + for (int i = 0; i < levelHeightValue; i++) { - JSONArray creditArray = new JSONArray(); + creditArray.put(finalQuorumSignsArray); + } - for (int i = 0; i < levelHeight(); i++) { + qOut[s].println(creditArray); - creditArray.put(finalQuorumSignsArray); - } + stakeComplete = true; + } else { - qOut[s].println(creditArray); + InitiatorConsensusLogger.debug("sending null for slow quorum"); + qOut[s].println("null"); + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); + } - stakeComplete = true; } else { InitiatorConsensusLogger.debug("sending null for slow quorum"); qOut[s].println("null"); IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); + "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); + } } else { - InitiatorConsensusLogger.debug("sending null for slow quorum"); + InitiatorConsensusLogger.debug("sending null for slow quorum "); qOut[s].println("null"); IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); + "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); } - - } else { - - InitiatorConsensusLogger.debug("sending null for slow quorum "); - qOut[s].println("null"); - IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); - + } catch (SocketException e) { + InitiatorConsensusLogger + .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumPID[s] + + " is unable to Respond!"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + + signedAlphaQuorumPID[s]); } - } catch (SocketException e) { - InitiatorConsensusLogger - .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumID[s] - + " is unable to Respond!"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + - signedAlphaQuorumID[s]); } } catch (Exception e) { diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 1e667a8e..fea519f1 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -4,7 +4,7 @@ import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; import static com.rubix.Constants.MiningConstants.MINE_ID; import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; -import static com.rubix.Constants.MiningConstants.MINING_TID; +import static com.rubix.Constants.MiningConstants.MINE_TID; import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Resources.Functions.DATA_PATH; @@ -275,7 +275,7 @@ STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", tokenHash)); stakingSigns.put( MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineDetToSign.getString(MINING_TID))); + mineDetToSign.getString(MINE_TID))); stakingSigns.put( MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", mineDetToSign.getString(MINED_RBT))); @@ -284,7 +284,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", out.println(stakingSigns.toString()); } else { - QuorumConsensusLogger.debug("Stake ID: Null"); + QuorumConsensusLogger.debug("Mine ID: Null"); } boolean flag = true; diff --git a/src/com/rubix/Constants/MiningConstants.java b/src/com/rubix/Constants/MiningConstants.java index ed53bcdc..70850e1c 100644 --- a/src/com/rubix/Constants/MiningConstants.java +++ b/src/com/rubix/Constants/MiningConstants.java @@ -2,7 +2,7 @@ public class MiningConstants { - public static final String MINING_TID = "mineTransactionID"; + public static final String MINE_TID = "mineTransactionID"; public static final String MINED_RBT = "minedToken"; public static final String MINE_ID = "mineID"; public static final String STAKED_QUORUM_DID = "stakedQuorumDID"; From 039478dd119590bbe81f4cd45ff6dbeb161aa851 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 4 Mar 2022 11:35:45 +0530 Subject: [PATCH 014/179] better comments Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/InitiatorConsensus.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 10b47b1f..35018f78 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -56,7 +56,6 @@ public class InitiatorConsensus { public static volatile JSONObject quorumSignature = new JSONObject(); public static volatile JSONObject stakingSignature = new JSONObject(); private static final Object countLock = new Object(); - private static final Object stakeLock = new Object(); private static final Object signLock = new Object(); public static ArrayList quorumWithShares = new ArrayList<>(); public static volatile int[] quorumResponse = { 0, 0, 0 }; @@ -520,6 +519,10 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri JSONArray creditArray = new JSONArray(); + InitiatorConsensusLogger.debug("Staking Successful at index " + s); + InitiatorConsensusLogger + .debug("Sending Credits to DID: " + stakingQuorumDID); + for (int i = 0; i < levelHeightValue; i++) { creditArray.put(finalQuorumSignsArray); From 8b73b979f0e7f79b2b7355e616cb1c6ada3adf74 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 9 Mar 2022 12:31:54 +0530 Subject: [PATCH 015/179] Fix revert Signed-off-by: Nidhin Mahesh A --- .../rubix/Consensus/InitiatorConsensus.java | 278 ++++--- src/com/rubix/Constants/MiningConstants.java | 4 +- src/com/rubix/Resources/APIHandler.java | 697 +++++++++--------- 3 files changed, 527 insertions(+), 452 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index f0286973..35018f78 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -4,7 +4,7 @@ import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; import static com.rubix.Constants.MiningConstants.MINE_ID; import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; -import static com.rubix.Constants.MiningConstants.MINING_TID; +import static com.rubix.Constants.MiningConstants.MINE_TID; import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; @@ -56,12 +56,13 @@ public class InitiatorConsensus { public static volatile JSONObject quorumSignature = new JSONObject(); public static volatile JSONObject stakingSignature = new JSONObject(); private static final Object countLock = new Object(); - private static final Object stakeLock = 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 boolean stakeComplete = false; public static volatile JSONArray finalQuorumSignsArray = new JSONArray(); + public static JSONArray ownerSigns = new JSONArray(); + private static int levelHeightValue; /** * Added by Anuradha K on 04/01/20222. @@ -157,7 +158,7 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri PrintStream[] qOut = new PrintStream[QUORUM_COUNT]; BufferedReader[] qIn = new BufferedReader[QUORUM_COUNT]; String[] quorumID = new String[QUORUM_COUNT]; - String[] signedAlphaQuorumID = new String[minQuorum(7)]; + String[] signedAlphaQuorumPID = new String[7]; PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); JSONObject dataObject = new JSONObject(data); String hash = dataObject.getString("hash"); @@ -287,6 +288,28 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri } } } + + try { + qResponse[j] = qIn[j].readLine(); + } catch (SocketException e) { + InitiatorConsensusLogger + .warn("Quorum " + quorumID[j] + " is unable to Respond!"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); + } + + if (qResponse[j] != null) { + if (qResponse[j].equals("Auth_Failed")) { + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); + } else { + JSONObject signObject = new JSONObject(); + signObject.put("did", quorumID[j]); + signObject.put("hash", detailsToken.getString("ownerIdentity")); + signObject.put("signature", qResponse[j]); + ownerSigns.put(signObject); + + } + } + } else if (qResponse[j].equals("440")) { InitiatorConsensusLogger.debug("Credit Verification failed: Duplicates found"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); @@ -334,6 +357,11 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri InitiatorConsensusLogger.debug(role + " node authenticated at index " + index); boolean voteStatus = voteNCount(index, quorumSize); if (quorumResponse[index] <= minQuorum(quorumSize) && voteStatus) { + + if (j <= 7) { + signedAlphaQuorumPID[j] = quorumID[j]; + } + InitiatorConsensusLogger .debug("waiting for " + quorumSize + " +signs " + role); while (quorumResponse[index] < minQuorum(quorumSize)) { @@ -377,154 +405,164 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (operation.equals("new-credits-mining")) { - Thread[] stakingThreads = new Thread[signedAlphaQuorumID.length]; + levelHeightValue = levelHeight(); + + Thread[] stakingThreads = new Thread[signedAlphaQuorumPID.length]; // choosing a quorum member from 1 to 5 who have signed the transaction - for (int p = 0; p < signedAlphaQuorumID.length; p++) { + for (int p = 0; p < signedAlphaQuorumPID.length; p++) { int s = p; stakingThreads[p] = new Thread(() -> { try { - InitiatorConsensusLogger.debug( - "Contacting Signed Alpha Quorum ID : " + signedAlphaQuorumID[s] - + " for staking. Index: " + s); - - qSocket[s] = new Socket("127.0.0.1", PORT + s); - qSocket[s].setSoTimeout(socketTimeOut); - qIn[s] = new BufferedReader(new InputStreamReader(qSocket[s].getInputStream())); - qOut[s] = new PrintStream(qSocket[s].getOutputStream()); - - qOut[s].println("stake-token"); - try { - - qResponse[s] = qIn[s].readLine(); - // convert to JSON array - JSONArray stakingTokenDetals = new JSONArray(qResponse[s]); - // get token chain and token ID from the array - String stakingTokenHash = stakingTokenDetals.getString(0); - JSONArray stakingTokenChain = stakingTokenDetals.getJSONArray(1); - - String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", - "peerid", signedAlphaQuorumID[s]); - if (checkTokenOwnershiByDID(stakingTokenHash, stakingQuorumDID) - && stakingTokenChain.length() > levelHeight()) { - - InitiatorConsensusLogger.debug("Staking Token Received and Verified from " - + signedAlphaQuorumID[s] + " " + qResponse[s]); - - String mineID = getMineID(stakingTokenHash, ipfs); - InitiatorConsensusLogger - .debug("Sending mine ID to miner :" + mineID); - JSONObject detToSign = new JSONObject(); - detToSign.put(MINE_ID, stakingTokenHash); - detToSign.put(MINING_TID, stakingQuorumDID); - detToSign.put(MINED_RBT, stakingTokenHash); - qOut[s].println(detToSign.toString()); + if (signedAlphaQuorumPID[s] != null) { + InitiatorConsensusLogger.debug( + "Contacting Signed Alpha Quorum Peer : " + signedAlphaQuorumPID[s] + + " for staking. Index: " + s); + + qSocket[s] = new Socket("127.0.0.1", PORT + s); + qSocket[s].setSoTimeout(socketTimeOut); + qIn[s] = new BufferedReader(new InputStreamReader(qSocket[s].getInputStream())); + qOut[s] = new PrintStream(qSocket[s].getOutputStream()); + + qOut[s].println("stake-token"); + try { + + qResponse[s] = qIn[s].readLine(); + // convert to JSON array + JSONArray stakingTokenDetals = new JSONArray(qResponse[s]); + // get token chain and token ID from the array + String stakingTokenHash = stakingTokenDetals.getString(0); + JSONArray stakingTokenChain = stakingTokenDetals.getJSONArray(1); + + String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", + "peerid", signedAlphaQuorumPID[s]); + if (checkTokenOwnershiByDID(stakingTokenHash, stakingQuorumDID) + && stakingTokenChain.length() > levelHeightValue) { + + InitiatorConsensusLogger.debug("Staking Token Received and Verified from " + + signedAlphaQuorumPID[s] + " " + qResponse[s]); + + String mineID = getMineID(stakingTokenHash, ipfs); + InitiatorConsensusLogger + .debug("Sending mine ID to miner :" + mineID); + JSONObject detToSign = new JSONObject(); + detToSign.put(MINE_ID, mineID); + detToSign.put(MINE_TID, detailsToken.getString("Tid")); + detToSign.put(MINED_RBT, detailsToken.getString("token")); + qOut[s].println(detToSign.toString()); + + JSONObject stakingQuorumSigned = new JSONObject(); + + try { + qResponse[s] = qIn[s].readLine(); + // convert to JSON array + stakingQuorumSigned = new JSONObject(qResponse[s]); + InitiatorConsensusLogger.debug("Signature for Mining ID Received from " + + signedAlphaQuorumPID[s] + " " + qResponse[s]); + } catch (SocketException e) { + InitiatorConsensusLogger + .warn("Quorum " + quorumID[s] + " is unable to Respond!"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); + } - JSONObject stakingQuorumSigned = new JSONObject(); + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakingQuorumDID); + detailsToVerify.put("hash", mineID); + detailsToVerify.put("signature", stakingQuorumSigned.getString(MINE_ID_SIGN)); + + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + stakingSignature.put(MINE_TID, detailsToken.getString("Tid")); + stakingSignature.put(MINED_RBT, detailsToken.getString("token")); + stakingSignature.put(MINE_ID, mineID); + stakingSignature.put(STAKED_QUORUM_DID, stakingQuorumDID); + stakingSignature.put(STAKED_TOKEN, stakingTokenHash); + + stakingSignature.put(STAKED_TOKEN_SIGN, stakingQuorumSigned.getString( + STAKED_TOKEN_SIGN)); + stakingSignature.put(MINING_TID_SIGN, stakingQuorumSigned.getString( + MINING_TID_SIGN)); + stakingSignature.put(MINED_RBT_SIGN, stakingQuorumSigned.getString( + MINED_RBT_SIGN)); + stakingSignature.put(MINE_ID_SIGN, + stakingQuorumSigned.getString(MINE_ID_SIGN)); + + if (!stakeComplete) { + FileWriter shareWriter = new FileWriter( + new File(LOGGER_PATH + "mineID.txt"), + true); + shareWriter.write(detailsToVerify.toString(0)); + shareWriter.close(); + File readMineID = new File(LOGGER_PATH + "mineID.txt"); + String mineData = add(readMineID.toString(), ipfs); + pin(mineData, ipfs); + + File mineIDFile = new File( + WALLET_DATA_PATH.concat("/Stakes/").concat(mineData) + .concat(".json")); + if (!mineIDFile.exists()) + mineIDFile.createNewFile(); + writeToFile(mineIDFile.toString(), qResponse[s], false); + + InitiatorConsensusLogger.debug("Mine object: " + mineData); + deleteFile(LOGGER_PATH + "mineID.txt"); + + InitiatorConsensusLogger.debug("Staking Successful at index " + s); - try { - qResponse[s] = qIn[s].readLine(); - // convert to JSON array - stakingQuorumSigned = new JSONObject(qResponse[s]); - InitiatorConsensusLogger.debug("Signature for Mining ID Received from " - + signedAlphaQuorumID[s] + " " + qResponse[s]); - } catch (SocketException e) { - InitiatorConsensusLogger - .warn("Quorum " + quorumID[s] + " is unable to Respond!"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); - } + IPFSNetwork + .executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakingQuorumDID); - detailsToVerify.put("hash", mineID); - detailsToVerify.put("signature", stakingQuorumSigned.getString(MINE_ID_SIGN)); + JSONObject stakingInfo = new JSONObject(); + stakingInfo.put("StakerDID", stakingQuorumDID); + stakingInfo.put("StakedokenID", stakingTokenHash); + stakingInfo.put("minedToken", detailsToken); - if (Authenticate.verifySignature(detailsToVerify.toString())) { + JSONArray creditArray = new JSONArray(); - stakingSignature.put(MINING_TID, detailsToken.getString("Tid")); - stakingSignature.put(MINED_RBT, detailsToken.getString("token")); - stakingSignature.put(MINE_ID, mineID); - stakingSignature.put(STAKED_QUORUM_DID, stakingQuorumDID); - stakingSignature.put(STAKED_TOKEN, stakingTokenHash); - - stakingSignature.put(STAKED_TOKEN_SIGN, stakingQuorumSigned.getString( - STAKED_TOKEN_SIGN)); - stakingSignature.put(MINING_TID_SIGN, stakingQuorumSigned.getString( - MINING_TID_SIGN)); - stakingSignature.put(MINED_RBT_SIGN, stakingQuorumSigned.getString( - MINED_RBT_SIGN)); - stakingSignature.put(MINE_ID_SIGN, stakingQuorumSigned.getString(MINE_ID_SIGN)); - - if (!stakeComplete) { - FileWriter shareWriter = new FileWriter( - new File(LOGGER_PATH + "mineID.txt"), - true); - shareWriter.write(detailsToVerify.toString(0)); - shareWriter.close(); - File readMineID = new File(LOGGER_PATH + "mineID.txt"); - String mineData = add(readMineID.toString(), ipfs); - pin(mineData, ipfs); - - File mineIDFile = new File( - WALLET_DATA_PATH.concat("/Stakes/").concat(mineData) - .concat(".json")); - if (!mineIDFile.exists()) - mineIDFile.createNewFile(); - writeToFile(mineIDFile.toString(), qResponse[s], false); - - InitiatorConsensusLogger.debug("Mine object: " + mineData); - deleteFile(LOGGER_PATH + "mineID.txt"); - - InitiatorConsensusLogger.debug("Staking Successful at index " + s); + InitiatorConsensusLogger.debug("Staking Successful at index " + s); + InitiatorConsensusLogger + .debug("Sending Credits to DID: " + stakingQuorumDID); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); + for (int i = 0; i < levelHeightValue; i++) { - JSONObject stakingInfo = new JSONObject(); - stakingInfo.put("StakerDID", stakingQuorumDID); - stakingInfo.put("StakedokenID", stakingTokenHash); - stakingInfo.put("minedToken", detailsToken); + creditArray.put(finalQuorumSignsArray); + } - JSONArray creditArray = new JSONArray(); + qOut[s].println(creditArray); - for (int i = 0; i < levelHeight(); i++) { + stakeComplete = true; + } else { - creditArray.put(finalQuorumSignsArray); + InitiatorConsensusLogger.debug("sending null for slow quorum"); + qOut[s].println("null"); + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); } - qOut[s].println(creditArray); - - stakeComplete = true; } else { InitiatorConsensusLogger.debug("sending null for slow quorum"); qOut[s].println("null"); IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); + "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); + } } else { - InitiatorConsensusLogger.debug("sending null for slow quorum"); + InitiatorConsensusLogger.debug("sending null for slow quorum "); qOut[s].println("null"); IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); + "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); } - - } else { - - InitiatorConsensusLogger.debug("sending null for slow quorum "); - qOut[s].println("null"); - IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumID[s]); - + } catch (SocketException e) { + InitiatorConsensusLogger + .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumPID[s] + + " is unable to Respond!"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + + signedAlphaQuorumPID[s]); } - } catch (SocketException e) { - InitiatorConsensusLogger - .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumID[s] - + " is unable to Respond!"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + - signedAlphaQuorumID[s]); } } catch (Exception e) { diff --git a/src/com/rubix/Constants/MiningConstants.java b/src/com/rubix/Constants/MiningConstants.java index ed53bcdc..a06ed743 100644 --- a/src/com/rubix/Constants/MiningConstants.java +++ b/src/com/rubix/Constants/MiningConstants.java @@ -2,7 +2,7 @@ public class MiningConstants { - public static final String MINING_TID = "mineTransactionID"; + public static final String MINE_TID = "mineTransactionID"; public static final String MINED_RBT = "minedToken"; public static final String MINE_ID = "mineID"; public static final String STAKED_QUORUM_DID = "stakedQuorumDID"; @@ -11,4 +11,4 @@ public class MiningConstants { public static final String MINING_TID_SIGN = "TIDSignature"; public static final String MINED_RBT_SIGN = "minedTokenSignature"; public static final String MINE_ID_SIGN = "mineIDSignature"; -} +} \ No newline at end of file diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 14e22c13..a21bcc8e 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -135,42 +135,203 @@ public static JSONObject create(int type) throws Exception { } /** - * A call to get details of a transaction given its ID + * A method to add and host your DID ans Public share to ipfs * - * @param txnId - * @return Transaction Details - * @throws JSONException handles JSON Exceptions + * @files DID.json, DataTable.json, DID.png, PublicShare.png */ - public static JSONArray transactionDetails(String txnId) throws JSONException { - String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); - JSONObject countResult = new JSONObject(); + 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); + + } + + /** + * A call to sync all the nodes in the network + * + * @return Message if failed or succeeded + * @throws IOException + * @files DataTable.json + */ + public static String networkInfo() throws IOException, JSONException { + StringBuilder result = new StringBuilder(); JSONArray resultArray = new JSONArray(); - if (transactionHistory.length() == 0) { - countResult.put("Message", "No transactions found"); - resultArray.put(countResult); - return resultArray; + JSONObject jsonObject = new JSONObject(); + int syncFlag = 0; + URL url = new URL(SYNC_IP + "/get"); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + + while ((line = rd.readLine()) != null) { + result.append(line); + syncFlag = 1; } - JSONArray transArray = new JSONArray(transactionHistory); - JSONObject obj = new JSONObject(); - for (int i = 0; i < transArray.length(); i++) { - obj = transArray.getJSONObject(i); - if (obj.get("txn").equals(txnId)) { - obj.remove("essentialShare"); + rd.close(); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); - else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); - } + writeToFile(DATA_PATH + "DataTable.json", result.toString(), false); + if (syncFlag == 1) { + jsonObject.put("message", "Synced Successfully!"); + } else { + jsonObject.put("message", "Not synced! Try again after sometime."); + } + resultArray.put(jsonObject); + return resultArray.toString(); + } - resultArray.put(obj); + /** + * Method to query the credits information + * + * @throws JSONException + * + * @files QuorumSignedTransactions.json, MinedCreditsHistory.json + */ + public static JSONObject creditsInfo() throws JSONException { + String qstFile = WALLET_DATA_PATH.concat("QuorumSignedTransactions.json"); + String mineFile = WALLET_DATA_PATH.concat("MinedCreditsHistory.json"); + + File quorumFile = new File(qstFile); + File minedFile = new File(mineFile); + + int spentCredits = 0; + int unspentCredits = 0; + if (quorumFile.exists()) { + String qFile = readFile(qstFile); + JSONArray qArray = new JSONArray(qFile); + unspentCredits = qArray.length(); + } + if (minedFile.exists()) { + String mFile = readFile(mineFile); + JSONArray mArray = new JSONArray(mFile); + spentCredits = mArray.length(); + } + + JSONObject returnObject = new JSONObject(); + returnObject.put("spentCredits", spentCredits); + returnObject.put("unspentCredits", unspentCredits); + + return returnObject; + } + + /** + * A call to close all open IPFS streams + */ + public static void closeStreams() { + executeIPFSCommands("ipfs p2p close --all"); + } + + 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")) + count++; + } + return count; + } + + public static ArrayList swarmPeersList() throws IOException, InterruptedException { + String OS = getOsName(); + String[] command = new String[3]; + if (OS.contains("Mac") || OS.contains("Linux")) { + command[0] = "bash"; + command[1] = "-c"; + } else if (OS.contains("Windows")) { + command[0] = "cmd.exe"; + command[1] = "/c"; + } + command[2] = "export PATH=/usr/local/bin:$PATH && ipfs swarm peers"; + + Process P = Runtime.getRuntime().exec(command); + BufferedReader br = new BufferedReader(new InputStreamReader(P.getInputStream())); + + ArrayList peersArray = new ArrayList(); + String line; + while ((line = br.readLine()) != null) { + peersArray.add(line); + } + if (!OS.contains("Windows")) + P.waitFor(); + br.close(); + P.destroy(); + + ArrayList peersIdentities = new ArrayList(); + if (peersArray.size() != 0) { + List k = ipfs.swarm.peers(); + 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 + */ + public static JSONArray peersOnlineStatus() throws JSONException, IOException, InterruptedException { + ArrayList peersArray = swarmPeersList(); + String dataTable = readFile(DATA_PATH + "DataTable.json"); + JSONArray dataArray = new JSONArray(dataTable); + JSONArray onlinePeers = new JSONArray(); + + for (int i = 0; i < dataArray.length(); i++) { + JSONObject peerObject = dataArray.getJSONObject(i); + String peerID = peerObject.getString("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 { + JSONObject onlinePeersObject = new JSONObject(); + onlinePeersObject.put("did", getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID)); + onlinePeersObject.put("onlineStatus", "offline"); + onlinePeers.put(onlinePeersObject); } } - APILogger.info("Transaction Details for : " + obj.toString()); - return resultArray; + + return onlinePeers; + } + + /** + * A call to list out all contacts in the user wallet + * + * @return A list of user wallet contacts + * @throws JSONException handles JSON Exceptions + */ + 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++) { + didArray.put(dataArray.getJSONObject(i).getString("didHash")); + } + return didArray; + } + + public static JSONObject syncNetworkNodes() throws JSONException, IOException { + String dataTable = readFile(DATA_PATH + "DataTable.json"); + 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); + + return new JSONObject("{\"message\":\"Synced all nodes\"}"); } /** @@ -178,6 +339,7 @@ public static JSONArray transactionDetails(String txnId) throws JSONException { * * @return Detailed explanation of the account information of the user * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json, DID.json */ public static JSONArray accountInformation() throws JSONException { int txnAsSender = 0, txnAsReceiver = 0; @@ -219,53 +381,80 @@ public static JSONArray accountInformation() throws JSONException { } /** - * A method to add and host your DID ans Public share to ipfs + * A call to list out number of transactions made per day + * + * @return List of transactions committed on every date + * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ - 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); + public static JSONArray txnPerDay() throws JSONException { + String dataTableFileContent = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); + JSONArray dataTable = new JSONArray(dataTableFileContent); + HashSet dateSet = new HashSet<>(); + for (int i = 0; i < dataTable.length(); i++) + dateSet.add(dataTable.getJSONObject(i).getString("Date")); - add(DATA_PATH.concat(didHash).concat("/DID.png"), ipfs); - pin(didHash, ipfs); + JSONObject datesTxn = new JSONObject(); + Iterator dateIterator = dateSet.iterator(); + while (dateIterator.hasNext()) { + String date = dateIterator.next(); + int count = 0; + for (int i = 0; i < dataTable.length(); i++) { + JSONObject obj = dataTable.getJSONObject(i); - add(DATA_PATH.concat(didHash).concat("/PublicShare.png"), ipfs); - pin(walletHash, ipfs); + if (date.equals(obj.getString("Date"))) { + count++; + } + } + datesTxn.put(date, count); + + } + return new JSONArray().put(datesTxn); } /** - * A call to sync all the nodes in the network + * A call to get details of a transaction given its ID * - * @return Message if failed or succeeded - * @throws IOException + * @param txnId Transaction ID + * @return Transaction Details + * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ - public static String networkInfo() throws IOException, JSONException { - StringBuilder result = new StringBuilder(); + public static JSONArray transactionDetails(String txnId) throws JSONException { + String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); + JSONObject countResult = new JSONObject(); JSONArray resultArray = new JSONArray(); - JSONObject jsonObject = new JSONObject(); - int syncFlag = 0; - URL url = new URL(SYNC_IP + "/get"); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - - while ((line = rd.readLine()) != null) { - result.append(line); - syncFlag = 1; + if (transactionHistory.length() == 0) { + countResult.put("Message", "No transactions found"); + resultArray.put(countResult); + return resultArray; } - rd.close(); + JSONArray transactionArray = new JSONArray(transactionHistory); + JSONObject transactionObject = new JSONObject(); + for (int i = 0; i < transactionArray.length(); i++) { + transactionObject = transactionArray.getJSONObject(i); + if (transactionObject.get("txn").equals(txnId)) { + transactionObject.remove("essentialShare"); + + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); + else { + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); + } + + resultArray.put(transactionObject); + } - writeToFile(DATA_PATH + "DataTable.json", result.toString(), false); - if (syncFlag == 1) { - jsonObject.put("message", "Synced Successfully!"); - } else { - jsonObject.put("message", "Not synced! Try again after sometime."); } - resultArray.put(jsonObject); - return resultArray.toString(); + APILogger.info("Transaction Details for : " + transactionObject.toString()); + return resultArray; } /** @@ -275,6 +464,7 @@ public static String networkInfo() throws IOException, JSONException { * @param e End Date * @return List of transactions * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ public static JSONArray transactionsByDate(String s, String e) throws JSONException, ParseException { JSONArray resultArray = new JSONArray(); @@ -287,8 +477,6 @@ public static JSONArray transactionsByDate(String s, String e) throws JSONExcept JSONObject countResult = new JSONObject(); Date startDate = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").parse(startDateString); Date endDate = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").parse(endDateString); - APILogger.debug("start date is " + startDate); - APILogger.debug("end date is " + endDate); File fileCheck1 = new File(WALLET_DATA_PATH + "TransactionHistory.json"); if (!fileCheck1.exists()) { countResult.put("Message", "File not found"); @@ -297,32 +485,37 @@ public static JSONArray transactionsByDate(String s, String e) throws JSONExcept } String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); - APILogger.debug(transArray.length()); if (transArray.length() == 0) { countResult.put("Message", "No Transactions made yet"); resultArray.put(countResult); return resultArray; } - JSONObject obj; + JSONObject transactionObject; for (int i = 0; i < transArray.length(); i++) { - obj = transArray.getJSONObject(i); - String dateFromTxnHistoryString = obj.get("Date").toString(); - Date dateTH = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(dateFromTxnHistoryString); - String dateTHS = objSDF.format(dateTH); - Calendar c = Calendar.getInstance(); - c.setTime(objSDF.parse(dateTHS)); - dateTH = c.getTime(); - if (dateTH.after(startDate) && dateTH.before(endDate)) { - obj.remove("essentialShare"); - - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); - else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + transactionObject = transArray.getJSONObject(i); + String dateFromTxnHistoryString = transactionObject.get("Date").toString(); + if (dateFromTxnHistoryString.length() != 10) { + Date dateTH = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(dateFromTxnHistoryString); + String dateTHS = objSDF.format(dateTH); + Calendar c = Calendar.getInstance(); + c.setTime(objSDF.parse(dateTHS)); + dateTH = c.getTime(); + if (dateTH.after(startDate) && dateTH.before(endDate)) { + transactionObject.remove("essentialShare"); + + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); + else { + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); + } + + resultArray.put(transactionObject); } - - resultArray.put(obj); } } @@ -335,6 +528,7 @@ public static JSONArray transactionsByDate(String s, String e) throws JSONExcept * @param n Count * @return List of transactions * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ public static JSONArray transactionsByCount(int n) throws JSONException { @@ -351,7 +545,7 @@ public static JSONArray transactionsByCount(int n) throws JSONException { } String transactionHistory = readFile(path); JSONArray transArray = new JSONArray(transactionHistory); - JSONObject obj = new JSONObject(); + JSONObject transactionObject; if (transArray.length() == 0) { countResult.put("Message", "No transactions made yet"); resultArray.put(countResult); @@ -360,31 +554,39 @@ public static JSONArray transactionsByCount(int n) throws JSONException { if (n >= transArray.length()) { for (int i = transArray.length() - 1; i >= 0; i--) { - obj = transArray.getJSONObject(i); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + transactionObject = transArray.getJSONObject(i); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - resultArray.put(obj); + resultArray.put(transactionObject); } return resultArray; } for (int i = 1; i <= n; i++) { - obj = transArray.getJSONObject(transArray.length() - i); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + transactionObject = transArray.getJSONObject(transArray.length() - i); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - resultArray.put(obj); + resultArray.put(transactionObject); } return resultArray; } @@ -396,11 +598,12 @@ public static JSONArray transactionsByCount(int n) throws JSONException { * @param end end index * @return List of transactions * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ public static JSONArray transactionsByRange(int start, int end) throws JSONException { JSONObject countResult = new JSONObject(); JSONArray resultArray = new JSONArray(); - if (start <= 0 || end <= 0) { + if (start < 0 || end <= 0) { countResult.put("Message", "Count can't be null or negative"); resultArray.put(countResult); return resultArray; @@ -427,122 +630,89 @@ public static JSONArray transactionsByRange(int start, int end) throws JSONExcep if (!(end < transArray.length())) { for (int i = start; i < transArray.length(); i++) { - JSONObject obj = transArray.getJSONObject(i); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + JSONObject transactionObject = transArray.getJSONObject(i); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - resultArray.put(obj); + resultArray.put(transactionObject); } } else { if (start == end) { - JSONObject obj = transArray.getJSONObject(start); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + JSONObject transactionObject = transArray.getJSONObject(start); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - resultArray.put(obj); - } - for (int i = start; i < end; i++) { - JSONObject obj = transArray.getJSONObject(i); - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); - else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + resultArray.put(transactionObject); + } else { + for (int i = start; i <= end; i++) { + JSONObject transactionObject = transArray.getJSONObject(i); + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); + else { + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); + } + resultArray.put(transactionObject); } - - resultArray.put(obj); } } return resultArray; } - /** - * @throws JSONException - * - */ - public static JSONObject creditsInfo() throws JSONException { - // String thFile = WALLET_DATA_PATH.concat("TransactionHistory.json"); - String qstFile = WALLET_DATA_PATH.concat("QuorumSignedTransactions.json"); - String mineFile = WALLET_DATA_PATH.concat("MinedCreditsHistory.json"); - - // File txnFile = new File(thFile); - File quorumFile = new File(qstFile); - File minedFile = new File(mineFile); - - // int txnCount = 0; - // if(txnFile.exists()){ - // String transactionFile = - // readFile(WALLET_DATA_PATH.concat("TransactionHistory.json")); - // JSONArray txnArray = new JSONArray(transactionFile); - // txnCount = txnArray.length(); - // - // } - int spentCredits = 0; - int unspentCredits = 0; - if (quorumFile.exists()) { - String qFile = readFile(qstFile); - JSONArray qArray = new JSONArray(qFile); - unspentCredits = qArray.length(); - } - if (minedFile.exists()) { - String mFile = readFile(mineFile); - JSONArray mArray = new JSONArray(mFile); - spentCredits = mArray.length(); - } - - JSONObject returnObject = new JSONObject(); - // returnObject.put("txnCount",txnCount); - returnObject.put("spentCredits", spentCredits); - returnObject.put("unspentCredits", unspentCredits); - - return returnObject; - } - - /** - * A call to close all open IPFS streams - */ - 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 + * @files TransactionHistory.json */ public static JSONArray transactionsByComment(String comment) throws JSONException { String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); - JSONObject obj; + JSONObject transactionObject; JSONArray resultArray = new JSONArray(); for (int i = 0; i < transArray.length(); i++) { - obj = transArray.getJSONObject(i); - - if (obj.get("comment").equals(comment)) { - obj.remove("essentialShare"); - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); + transactionObject = transArray.getJSONObject(i); + + if (transactionObject.get("comment").equals(comment)) { + transactionObject.remove("essentialShare"); + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); } - - resultArray.put(obj); + resultArray.put(transactionObject); } } @@ -561,166 +731,33 @@ public static JSONArray transactionsByComment(String comment) throws JSONExcepti * @param did DID of the contact * @return List of transactions committed with the user DID * @throws JSONException handles JSON Exceptions + * @files TransactionHistory.json */ public static JSONArray transactionsByDID(String did) throws JSONException { String transactionHistory = readFile(WALLET_DATA_PATH + "TransactionHistory.json"); JSONArray transArray = new JSONArray(transactionHistory); JSONArray resultArray = new JSONArray(); for (int i = 0; i < transArray.length(); i++) { - JSONObject obj = transArray.getJSONObject(i); - obj.remove("essentialShare"); + JSONObject transactionObject = transArray.getJSONObject(i); + transactionObject.remove("essentialShare"); + + if (transactionObject.get("senderDID").equals(did) || transactionObject.get("receiverDID").equals(did)) { + if (transactionObject.has("amount-received")) { + transactionObject.put("amount", transactionObject.getDouble("amount-received")); + } else if (transactionObject.has("amount-spent")) { + transactionObject.put("amount", transactionObject.getDouble("amount-spent")); + } else if (transactionObject.has("amount")) + transactionObject.put("amount", transactionObject.getDouble("amount")); + else { + JSONArray tokensArray = (JSONArray) transactionObject.get("tokens"); + transactionObject.put("amount", tokensArray.length()); + } - if (obj.has("amount")) - obj.put("amount", obj.getDouble("amount")); - else { - JSONArray tokensArray = (JSONArray) obj.get("tokens"); - obj.put("amount", tokensArray.length()); + resultArray.put(transactionObject); } - - resultArray.put(obj); - - if (obj.get("senderDID").equals(did) || obj.get("receiverDID").equals(did)) - resultArray.put(obj); } return resultArray; } - public static int onlinePeersCount() throws JSONException, IOException, InterruptedException { - JSONArray peersArray = peersOnlineStatus(); - int count = 0; - for (int i = 0; i < peersArray.length(); i++) { - if (peersArray.getJSONObject(i).getString("onlineStatus").contains("online")) - count++; - } - return count; - } - - public static ArrayList swarmPeersList() throws IOException, InterruptedException { - String OS = getOsName(); - String[] command = new String[3]; - if (OS.contains("Mac") || OS.contains("Linux")) { - command[0] = "bash"; - command[1] = "-c"; - } else if (OS.contains("Windows")) { - command[0] = "cmd.exe"; - command[1] = "/c"; - } - command[2] = "export PATH=/usr/local/bin:$PATH && ipfs swarm peers"; - - Process P = Runtime.getRuntime().exec(command); - BufferedReader br = new BufferedReader(new InputStreamReader(P.getInputStream())); - - ArrayList peersArray = new ArrayList(); - String line; - while ((line = br.readLine()) != null) { - peersArray.add(line); - } - if (!OS.contains("Windows")) - P.waitFor(); - br.close(); - P.destroy(); - - ArrayList peersIdentities = new ArrayList(); - if (peersArray.size() != 0) { - List k = ipfs.swarm.peers(); - 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 - */ - public static JSONArray peersOnlineStatus() throws JSONException, IOException, InterruptedException { - ArrayList peersArray = swarmPeersList(); - String dataTable = readFile(DATA_PATH + "DataTable.json"); - JSONArray dataArray = new JSONArray(dataTable); - JSONArray onlinePeers = new JSONArray(); - - for (int i = 0; i < dataArray.length(); i++) { - JSONObject peerObject = dataArray.getJSONObject(i); - String peerID = peerObject.getString("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 { - JSONObject onlinePeersObject = new JSONObject(); - onlinePeersObject.put("did", getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", peerID)); - onlinePeersObject.put("onlineStatus", "offline"); - onlinePeers.put(onlinePeersObject); - } - - } - - return onlinePeers; - } - - /** - * A call to list out all contacts in the user wallet - * - * @return A list of user wallet contacts - * @throws JSONException handles JSON Exceptions - */ - 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++) { - didArray.put(dataArray.getJSONObject(i).getString("didHash")); - } - return didArray; - } - - /** - * A call to list out number of transactions made per day - * - * @return List of transactions committed on every date - * @throws JSONException handles JSON Exceptions - */ - 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++) - dateSet.add(dataArray.getJSONObject(i).getString("Date")); - - JSONObject datesTxn = new JSONObject(); - Iterator dateIterator = dateSet.iterator(); - while (dateIterator.hasNext()) { - String date = dateIterator.next(); - int count = 0; - for (int i = 0; i < dataArray.length(); i++) { - JSONObject obj = dataArray.getJSONObject(i); - - if (date.equals(obj.getString("Date"))) { - count++; - } - } - datesTxn.put(date, count); - - } - - return new JSONArray().put(datesTxn); - } - - public static JSONObject syncNetworkNodes() throws JSONException, IOException { - String dataTable = readFile(DATA_PATH + "DataTable.json"); - 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); - - return new JSONObject("{\"message\":\"Synced all nodes\"}"); - } } From 611f74b3f2bc7ad087416bbda051b1b021e56a27 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 14 Mar 2022 16:21:37 +0530 Subject: [PATCH 016/179] initHash changes Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/InitiatorProcedure.java | 9 ++++++++- src/com/rubix/Consensus/QuorumConsensus.java | 2 +- src/com/rubix/Resources/Functions.java | 14 +++++++------- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorProcedure.java b/src/com/rubix/Consensus/InitiatorProcedure.java index a97bafc6..56c58bb4 100644 --- a/src/com/rubix/Consensus/InitiatorProcedure.java +++ b/src/com/rubix/Consensus/InitiatorProcedure.java @@ -3,6 +3,7 @@ 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.initHash; import static com.rubix.Resources.Functions.minQuorum; import java.io.IOException; @@ -39,12 +40,12 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); JSONObject dataObject = new JSONObject(data); + String initHash = null; 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 initHash = dataObject.getString("initHash"); String token = dataObject.getString("token"); JSONArray alphaList = dataObject.getJSONArray("alphaList"); JSONArray betaList = dataObject.getJSONArray("betaList"); @@ -53,6 +54,12 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz String authSenderByQuorumHash = calculateHash(message, "SHA3-256"); String authQuorumHash = calculateHash(authSenderByQuorumHash.concat(receiverDidIpfs), "SHA3-256"); + try { + initHash = initHash(); + } catch (IOException e1) { + InitiatorProcedureLogger.debug("Payload Split Success"); + } + try { payload.put("sender", senderDidIpfs); payload.put("token", token); diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index fea519f1..8bcea5e2 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -331,7 +331,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // ! match initiator initHash with quorum. if didn't match, reject - if (!initHash.equals(initHash())) { + if ((!initHash.equals(initHash())) && (initHash != null)) { QuorumConsensusLogger.debug("Initiator Hash Mismatch"); out.println("443"); socket.close(); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 6cbd8875..319db1af 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -76,11 +76,11 @@ public class Functions { public static Logger FunctionsLogger = Logger.getLogger(Functions.class); public static String buildVersion() throws IOException { - String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - initPath = initPath.split("\\.jar")[0]; - initPath = initPath + ".jar"; - String initHash = calculateFileHash(initPath, "MD5"); - return initHash; + String jarPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); + jarPath = jarPath.split("\\.jar")[0]; + jarPath = jarPath + ".jar"; + String hash = calculateFileHash(jarPath, "MD5"); + return hash; } public static String calculateFileHash(String filePath, String algorithm) { @@ -1172,8 +1172,8 @@ public static String initHash() throws IOException { String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); initPath = initPath.split("\\.jar")[0]; initPath = initPath + ".jar"; - String initHash = calculateFileHash(initPath, "SHA3-256"); - return initHash; + String hash = calculateFileHash(initPath, "SHA3-256"); + return hash; } public static int checkHeartBeat(String peerId, String appName) { From 03ca07dbcf56b97110a691dd45277a0fe9d86b88 Mon Sep 17 00:00:00 2001 From: Kiran H Date: Tue, 15 Mar 2022 17:06:51 +0530 Subject: [PATCH 017/179] checksum fix Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Resources/Functions.java | 28 +++++++++++++++++--------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 319db1af..5e00e999 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -78,6 +78,9 @@ public class Functions { public static String buildVersion() throws IOException { String jarPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); jarPath = jarPath.split("\\.jar")[0]; + jarPath = jarPath.split("file:", 2)[1]; + // trim first part of the string till first "/" + jarPath = jarPath + ".jar"; String hash = calculateFileHash(jarPath, "MD5"); return hash; @@ -88,17 +91,21 @@ public static String calculateFileHash(String filePath, String algorithm) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); System.out.println("File path: " + filePath); - System.out.println("File Hashing..."); - FileInputStream fis = new FileInputStream(filePath); - System.out.println("File read OK"); - byte[] dataBytes = new byte[1024]; - int nread = 0; - while ((nread = fis.read(dataBytes)) != -1) { - digest.update(dataBytes, 0, nread); + + // check if file exists at the filePath + File file = new File(filePath); + if (file.exists()) { + System.out.println("File Hashing..."); + FileInputStream fis = new FileInputStream(file); + byte[] byteArray = new byte[1024]; + int bytesCount = 0; + while ((bytesCount = fis.read(byteArray)) != -1) { + digest.update(byteArray, 0, bytesCount); + } + byte[] hashBytes = digest.digest(); + hash = bytesToHex(hashBytes); + fis.close(); } - byte[] hashBytes = digest.digest(); - hash = bytesToHex(hashBytes); - fis.close(); } catch (NoSuchAlgorithmException | IOException e) { FunctionsLogger.error("Invalid Cryptographic Algorithm", e); e.printStackTrace(); @@ -1171,6 +1178,7 @@ public static void mineUpdate(String didHash, int credits) throws IOException, J public static String initHash() throws IOException { String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); initPath = initPath.split("\\.jar")[0]; + initPath = initPath.split("file:", 2)[1]; initPath = initPath + ".jar"; String hash = calculateFileHash(initPath, "SHA3-256"); return hash; From b6a11dfe2cbda3d2a8fdd495aac8243fb85be2c7 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 16 Mar 2022 12:08:09 +0530 Subject: [PATCH 018/179] rec check merge Signed-off-by: Nidhin Mahesh A --- .../rubix/AuthenticateNode/SplitShares.java | 15 +- .../rubix/Consensus/InitiatorProcedure.java | 10 +- src/com/rubix/Consensus/QuorumConsensus.java | 142 +-------- src/com/rubix/Mining/ProofCredits.java | 99 +++++-- .../rubix/TokenTransfer/TokenReceiver.java | 275 +++++++++++------- src/com/rubix/TokenTransfer/TokenSender.java | 56 +++- 6 files changed, 293 insertions(+), 304 deletions(-) diff --git a/src/com/rubix/AuthenticateNode/SplitShares.java b/src/com/rubix/AuthenticateNode/SplitShares.java index 1ba367c0..4f0897f9 100644 --- a/src/com/rubix/AuthenticateNode/SplitShares.java +++ b/src/com/rubix/AuthenticateNode/SplitShares.java @@ -1,16 +1,15 @@ package com.rubix.AuthenticateNode; - -import io.ipfs.api.IPFS; -import org.apache.log4j.Logger; -import org.json.JSONArray; +import static com.rubix.Resources.Functions.IPFS_PORT; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; -import static com.rubix.Resources.Functions.IPFS_PORT; +import org.apache.log4j.Logger; +import org.json.JSONArray; +import io.ipfs.api.IPFS; public class SplitShares { public static Logger SplitSharesLogger = Logger.getLogger(SplitShares.class); @@ -20,9 +19,9 @@ public class SplitShares { public static JSONArray initiate; static JSONArray arr = new JSONArray(); - /** - * This is the main method to be called for converting the secret into binary and creating shares + * This is the main method to be called for converting the secret into binary + * and creating shares * * @param decentralizedID Secret string * @return Array of shares @@ -36,5 +35,3 @@ private static boolean generateShares(BufferedImage decentralizedID) throws IOEx } } - - diff --git a/src/com/rubix/Consensus/InitiatorProcedure.java b/src/com/rubix/Consensus/InitiatorProcedure.java index 56c58bb4..4b23b88e 100644 --- a/src/com/rubix/Consensus/InitiatorProcedure.java +++ b/src/com/rubix/Consensus/InitiatorProcedure.java @@ -40,7 +40,6 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); JSONObject dataObject = new JSONObject(data); - String initHash = null; String tid = dataObject.getString("tid"); String message = dataObject.getString("message"); String receiverDidIpfs = dataObject.getString("receiverDidIpfs"); @@ -54,12 +53,6 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz String authSenderByQuorumHash = calculateHash(message, "SHA3-256"); String authQuorumHash = calculateHash(authSenderByQuorumHash.concat(receiverDidIpfs), "SHA3-256"); - try { - initHash = initHash(); - } catch (IOException e1) { - InitiatorProcedureLogger.debug("Payload Split Success"); - } - try { payload.put("sender", senderDidIpfs); payload.put("token", token); @@ -85,12 +78,11 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz senderSignQ = getSignFromShares(pvt, authSenderByQuorumHash); data1.put("sign", senderSignQ); data1.put("senderDID", senderDidIpfs); - data1.put("initHash", initHash); + data1.put("initHash", initHash()); data1.put("token", token); data1.put(ConsensusConstants.TRANSACTION_ID, tid); data1.put(ConsensusConstants.HASH, authSenderByQuorumHash); data1.put(ConsensusConstants.RECEIVERID, receiverDidIpfs); - data1.put("ownerIdentity", dataObject.getString("ownerIdentity")); data2.put("Share1", Q1Share); data2.put("Share2", Q2Share); diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 8bcea5e2..8d532897 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,28 +1,16 @@ package com.rubix.Consensus; -import static com.rubix.Constants.MiningConstants.MINED_RBT; -import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; -import static com.rubix.Constants.MiningConstants.MINE_ID; -import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; -import static com.rubix.Constants.MiningConstants.MINE_TID; -import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; -import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; 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.PAYMENTS_PATH; 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.getPeerID; import static com.rubix.Resources.Functions.getSignFromShares; import static com.rubix.Resources.Functions.getValues; -import static com.rubix.Resources.Functions.initHash; 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; @@ -85,8 +73,7 @@ public QuorumConsensus(String role, int port) { public void run() { while (true) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - String peerID, transactionID, verifySenderHash, receiverDID, appName, stakingQuorumDID, - stakedToken, senderPrivatePos, initHash, token, + String peerID, transactionID, verifySenderHash, receiverDID, appName, senderPrivatePos, senderDidIpfsHash = "", senderPID = "", ownerHash = ""; ServerSocket serverSocket = null; Socket socket = null; @@ -218,88 +205,6 @@ public void run() { } else QuorumConsensusLogger.debug("Old Credits Mining / Whole RBT Token Transfer"); - // ! operation for quorum staking token starts here - - if (operation.equals("stake-token")) { - - QuorumConsensusLogger.debug("Initiating Token Staking for Newly Mined Token..."); - String mineID = null; - JSONArray tokenToStake = new JSONArray(); - - String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray bankArray = new JSONArray(bankFile); - - // pick last object from bank array - JSONObject bankObject = bankArray.getJSONObject(0); - String tokenHash = bankObject.getString("tokenHash"); - tokenToStake.put(tokenHash); - - File tokenFile = new File(TOKENS_PATH + tokenHash); - File tokenchainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); - - if (tokenFile.exists() && tokenchainFile.exists()) { - - String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); - tokenToStake.put(tokenChain); - - out.println(tokenToStake); - } else { - QuorumConsensusLogger.debug("Token Staking Failed: Details of Picked Token is Missing"); - out.println("443"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - - // move that token ID to bottom of BNK00 file - JSONObject mineDetToSign = new JSONObject(); - - try { - String mineData = in.readLine(); - // convert mineData to JSONObject - mineDetToSign = new JSONObject(mineData); - } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - Stake ID details"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - - if (mineDetToSign.length() > 0) { - JSONObject stakingSigns = new JSONObject(); - - QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); - - stakingSigns.put( - STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - tokenHash)); - stakingSigns.put( - MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineDetToSign.getString(MINE_TID))); - stakingSigns.put( - MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineDetToSign.getString(MINED_RBT))); - stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineDetToSign.getString(MINE_ID))); - - out.println(stakingSigns.toString()); - } else { - QuorumConsensusLogger.debug("Mine ID: Null"); - } - - boolean flag = true; - - if (flag) { - - } else { - out.println("442"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - // ! operation for quorum staking token ends here - } else - QuorumConsensusLogger.debug("Old Credits Mining / Whole RBT Token Transfer"); String getRecData = null; try { getRecData = in.readLine(); @@ -323,21 +228,6 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", transactionID = readSenderData.getString("Tid"); verifySenderHash = readSenderData.getString("Hash"); receiverDID = readSenderData.getString("RID"); - ownerHash = readSenderData.getString("ownerIdentity"); - - // ! additional info for the mining verification - initHash = readSenderData.getString("initHash"); - token = readSenderData.getString("token"); - - // ! match initiator initHash with quorum. if didn't match, reject - - if ((!initHash.equals(initHash())) && (initHash != null)) { - QuorumConsensusLogger.debug("Initiator Hash Mismatch"); - out.println("443"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } syncDataTable(senderDidIpfsHash, null); @@ -362,38 +252,13 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", 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())) { QuorumConsensusLogger.debug("Quorum Authenticated Sender"); QuorumConsensusLogger.debug("ConsensusID pass"); - // json obj called quorumSignss - JSONObject quorumSigns = new JSONObject(); - - // ! 1st sign: TID - String QuorumSignatureOne = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - transactionID); - quorumSigns.put("TIDSign", QuorumSignatureOne); - // ? - // ! 2st sign: Token - String QuorumSignatureTwo = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - token); - quorumSigns.put("TokenSign", QuorumSignatureTwo); - - // ! 3th sign: Token + TID - String QuorumSignatureThree = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", quorumHash); - quorumSigns.put("QuorumSign", QuorumSignatureThree); - - out.println(quorumSigns.toString()); - - String ownerSign = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", ownerHash); + out.println(QuorumSignature); String creditSignatures = null; try { @@ -442,7 +307,6 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", deleteFile(LOGGER_PATH + "consenusIDhash"); QuorumConsensusLogger.debug("added consensus ID " + consenusIDhash); } - out.println(ownerSign); } else { QuorumConsensusLogger.debug("Sender Authentication Failure - Quorum"); diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index dbd948c0..3ecfdfa0 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -17,6 +17,7 @@ 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.strToIntArray; import static com.rubix.Resources.Functions.updateJSON; import static com.rubix.Resources.Functions.updateQuorum; import static com.rubix.Resources.Functions.writeToFile; @@ -24,9 +25,11 @@ 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.DataOutputStream; import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; @@ -39,8 +42,10 @@ import java.util.Iterator; import java.util.List; +import javax.imageio.ImageIO; import javax.net.ssl.HttpsURLConnection; +import com.rubix.AuthenticateNode.PropImage; import com.rubix.Consensus.InitiatorConsensus; import com.rubix.Consensus.InitiatorProcedure; import com.rubix.Resources.Functions; @@ -66,7 +71,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON repo(ipfs); JSONObject APIResponse = new JSONObject(); JSONObject detailsObject = new JSONObject(data); - String receiverDidIpfsHash = detailsObject.getString("receiverDidIpfsHash"); + String DID = detailsObject.getString("receiverDidIpfsHash"); String pvt = detailsObject.getString("pvt"); int type = detailsObject.getInt("type"); int creditUsed = 0; @@ -162,14 +167,14 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONArray prooftid = new JSONArray(); String comments = resJsonData.toString() + prooftid; - String authSenderByRecHash = calculateHash(token + receiverDidIpfsHash + comments, "SHA3-256"); + String authSenderByRecHash = calculateHash(token + DID + comments, "SHA3-256"); String tid = calculateHash(authSenderByRecHash, "SHA3-256"); - writeToFile(LOGGER_PATH + "tempbeta", tid.concat(receiverDidIpfsHash), false); + writeToFile(LOGGER_PATH + "tempbeta", tid.concat(DID), false); String betaHash = IPFSNetwork.add(LOGGER_PATH + "tempbeta", ipfs); deleteFile(LOGGER_PATH + "tempbeta"); - writeToFile(LOGGER_PATH + "tempgamma", tid.concat(receiverDidIpfsHash), false); + writeToFile(LOGGER_PATH + "tempgamma", tid.concat(DID), false); String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); deleteFile(LOGGER_PATH + "tempgamma"); @@ -180,8 +185,7 @@ 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, DID, DID, token.length()); } } @@ -210,7 +214,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON if (alphaPeersList.size() < minQuorum(alphaSize) || betaPeersList.size() < 5 || gammaPeersList.size() < 5) { updateQuorum(quorumArray, null, false, type); - APIResponse.put("did", receiverDidIpfsHash); + APIResponse.put("did", DID); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); APIResponse.put("message", "Quorum Members not available"); @@ -253,7 +257,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON qstObject.put("credits", creditSignsArray); } else { updateQuorum(quorumArray, null, false, type); - APIResponse.put("did", receiverDidIpfsHash); + APIResponse.put("did", DID); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); APIResponse.put("message", "Credit File(s) missing"); @@ -264,9 +268,9 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONObject dataObject = new JSONObject(); dataObject.put("tid", tid); dataObject.put("message", comments); - dataObject.put("receiverDidIpfs", receiverDidIpfsHash); + dataObject.put("receiverDidIpfs", DID); dataObject.put("pvt", pvt); - dataObject.put("senderDidIpfs", receiverDidIpfsHash); + dataObject.put("senderDidIpfs", DID); dataObject.put("token", token.toString()); dataObject.put("alphaList", alphaPeersList); dataObject.put("betaList", betaPeersList); @@ -277,7 +281,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON "new-credits-mining"); if (!(InitiatorConsensus.quorumSignature.length() >= 3 * minQuorum(7))) { - APIResponse.put("did", receiverDidIpfsHash); + APIResponse.put("did", DID); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); APIResponse.put("message", "Consensus failed"); @@ -306,9 +310,9 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONObject dataObject = new JSONObject(); dataObject.put("tid", tid); dataObject.put("message", comments); - dataObject.put("receiverDidIpfs", receiverDidIpfsHash); + dataObject.put("receiverDidIpfs", DID); dataObject.put("pvt", pvt); - dataObject.put("senderDidIpfs", receiverDidIpfsHash); + dataObject.put("senderDidIpfs", DID); dataObject.put("token", token.toString()); dataObject.put("alphaList", alphaPeersList); dataObject.put("betaList", betaPeersList); @@ -317,7 +321,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 3, alphaSize, ""); if (!(InitiatorConsensus.quorumSignature.length() >= 3 * minQuorum(7))) { - APIResponse.put("did", receiverDidIpfsHash); + APIResponse.put("did", DID); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); APIResponse.put("message", "Consensus failed"); @@ -342,7 +346,54 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); deleteFile(LOGGER_PATH + "tempToken"); - writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", "[]", false); + + FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); + shareWriter.write(InitiatorConsensus.quorumSignature.toString()); + shareWriter.close(); + File readCredit = new File(LOGGER_PATH + "mycredit.txt"); + String credit = add(readCredit.toString(), ipfs); + + File creditFile = new File(WALLET_DATA_PATH.concat("/Credits/").concat(credit).concat(".json")); + if (!creditFile.exists()) + creditFile.createNewFile(); + writeToFile(creditFile.toString(), InitiatorConsensus.quorumSignature.toString(), false); + + String tokens = tokenHash; + String hashString = tokens.concat(DID); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + + BufferedImage privateImage = ImageIO + .read(new File(DATA_PATH.concat(DID).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(privateImage); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + String ownerIdentity = hashForPositions.concat(positions); + String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); + + ProofCreditsLogger.debug("Ownership Here"); + ProofCreditsLogger.debug("tokens: " + tokenHash); + ProofCreditsLogger.debug("hashString: " + hashString); + ProofCreditsLogger.debug("hashForPositions: " + hashForPositions); + ProofCreditsLogger.debug("p1: " + positions); + ProofCreditsLogger.debug("ownerIdentity: " + ownerIdentity); + ProofCreditsLogger.debug("ownerIdentityHash: " + ownerIdentityHash); + JSONArray tokenChainArray = new JSONArray(); + JSONObject tokenChainGenesisObject = new JSONObject(); + tokenChainGenesisObject.put("quorumSignatures", credit); + tokenChainGenesisObject.put("sender", DID); + tokenChainGenesisObject.put("comment", "Mining-Genesis"); + tokenChainGenesisObject.put("tid", tid); + tokenChainGenesisObject.put("owner", ownerIdentityHash); + tokenChainGenesisObject.put("blockNumber", 0); + tokenChainGenesisObject.put("nextHash", calculateHash(tid, "SHA3-256")); + tokenChainGenesisObject.put("previousHash", ""); + tokenChainArray.put(tokenChainGenesisObject); + + writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); JSONArray tempArray = new JSONArray(); @@ -381,8 +432,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON signedQuorumList.put(keys.next()); updateQuorum(quorumArray, signedQuorumList, true, type); - mineUpdate(receiverDidIpfsHash, creditUsed); - APIResponse.put("did", receiverDidIpfsHash); + mineUpdate(DID, creditUsed); + APIResponse.put("did", DID); APIResponse.put("tid", tid); APIResponse.put("token", token); APIResponse.put("creditsused", creditUsed); @@ -399,8 +450,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON transactionRecord.put("tokens", token); transactionRecord.put("txn", tid); transactionRecord.put("quorumList", signedQuorumList); - transactionRecord.put("senderDID", receiverDidIpfsHash); - transactionRecord.put("receiverDID", receiverDidIpfsHash); + transactionRecord.put("senderDID", DID); + transactionRecord.put("receiverDID", DID); transactionRecord.put("Date", currentTime); transactionRecord.put("totalTime", totalTime); transactionRecord.put("comment", "minedtxn"); @@ -425,7 +476,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // Serialization JSONObject dataToSend = new JSONObject(); dataToSend.put("bank_id", "01"); - dataToSend.put("user_did", receiverDidIpfsHash); + dataToSend.put("user_did", DID); dataToSend.put("token_id", token); dataToSend.put("level", level); dataToSend.put("denomination", 1); @@ -476,8 +527,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // Serialization JSONObject dataToSend = new JSONObject(); dataToSend.put("transaction_id", tid); - dataToSend.put("sender_did", receiverDidIpfsHash); - dataToSend.put("receiver_did", receiverDidIpfsHash); + dataToSend.put("sender_did", DID); + dataToSend.put("receiver_did", DID); dataToSend.put("token_id", tokenList); dataToSend.put("token_time", (int) totalTime); dataToSend.put("amount", tokenList.size()); @@ -512,7 +563,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.debug(responseTxn.toString()); } } else { - APIResponse.put("did", receiverDidIpfsHash); + APIResponse.put("did", DID); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); APIResponse.put("message", "error from mine service"); @@ -520,7 +571,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON return APIResponse; } } else { - APIResponse.put("did", receiverDidIpfsHash); + APIResponse.put("did", DID); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); APIResponse.put("message", "Insufficient proofs"); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 3218e0ea..6d7ef1af 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -14,11 +14,9 @@ import static com.rubix.Resources.Functions.formatAmount; import static com.rubix.Resources.Functions.getCurrentUtcTime; 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.pathSet; -import static com.rubix.Resources.Functions.randomPositions; import static com.rubix.Resources.Functions.readFile; import static com.rubix.Resources.Functions.strToIntArray; import static com.rubix.Resources.Functions.syncDataTable; @@ -200,46 +198,48 @@ public static String receive() { JSONArray partTokenChainsHash = TokenDetails.getJSONArray("hashSender"); JSONArray previousSendersArray = tokenObject.getJSONArray("previousSender"); + JSONArray positionsArray = tokenObject.getJSONArray("positions"); + Double amount = tokenObject.getDouble("amount"); JSONObject amountLedger = tokenObject.getJSONObject("amountLedger"); TokenReceiverLogger.debug("Amount Ledger: " + amountLedger); int intPart = wholeTokens.length(); - Double decimalPart = formatAmount(amount - intPart); - JSONArray doubleSpentToken = new JSONArray(); - JSONArray stakedToken = new JSONArray(); - boolean tokenOwners = true; - boolean incompleteStake = false; - ArrayList ownersArray = new ArrayList(); - ArrayList previousSender = new ArrayList(); - JSONArray ownersReceived = new JSONArray(); - for (int i = 0; i < wholeTokens.length(); ++i) { - try { - TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + " Please wait..."); - ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); - - if (ownersArray.size() > 2) { - - for (int j = 0; j < previousSendersArray.length(); j++) { - if (previousSendersArray.getJSONObject(j).getString("token") - .equals(wholeTokens.getString(i))) - ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); - } - - for (int j = 0; j < ownersReceived.length(); j++) { - previousSender.add(ownersReceived.getString(j)); - } - TokenReceiverLogger.debug("Previous Owners: " + previousSender); - - for (int j = 0; j < ownersArray.size(); j++) { - if (!previousSender.contains(ownersArray.get(j).toString())) - tokenOwners = false; - } - } - } catch (IOException e) { - - TokenReceiverLogger.debug("Ipfs dht find did not execute"); - } - } + // Double decimalPart = formatAmount(amount - intPart); + // JSONArray doubleSpentToken = new JSONArray(); + // boolean tokenOwners = true; + // ArrayList ownersArray = new ArrayList(); + // ArrayList previousSender = new ArrayList(); + // JSONArray ownersReceived = new JSONArray(); + // for (int i = 0; i < wholeTokens.length(); ++i) { + // try { + // TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + + // " Please wait..."); + // ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); + // + // if (ownersArray.size() > 2) { + // + // for (int j = 0; j < previousSendersArray.length(); j++) { + // if + // (previousSendersArray.getJSONObject(j).getString("token").equals(wholeTokens.getString(i))) + // ownersReceived = + // previousSendersArray.getJSONObject(j).getJSONArray("sender"); + // } + // + // for (int j = 0; j < ownersReceived.length(); j++) { + // previousSender.add(ownersReceived.getString(j)); + // } + // TokenReceiverLogger.debug("Previous Owners: " + previousSender); + // + // for (int j = 0; j < ownersArray.size(); j++) { + // if (!previousSender.contains(ownersArray.get(j).toString())) + // tokenOwners = false; + // } + // } + // } catch (IOException e) { + // + // TokenReceiverLogger.debug("Ipfs dht find did not execute"); + // } + // } // if (!tokenOwners) { // JSONArray owners = new JSONArray(); // for (int i = 0; i < ownersArray.size(); i++) @@ -261,16 +261,19 @@ public static String receive() { // ss.close(); // return APIResponse.toString(); // } + String senderToken = TokenDetails.toString(); + String consensusID = calculateHash(senderToken, "SHA3-256"); + writeToFile(LOGGER_PATH + "consensusID", consensusID, false); + String consensusIDIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "consensusID", ipfs); + deleteFile(LOGGER_PATH + "consensusID"); - if (incompleteStake) { - TokenReceiverLogger.debug("Token Height not reached for corresponding Staked Tokens " + stakedToken); - output.println("425"); - output.println(stakedToken.toString()); - output.println("Stake Incomplete"); + if (!IPFSNetwork.dhtEmpty(consensusIDIPFSHash, ipfs)) { + TokenReceiverLogger.debug("consensus ID not unique" + consensusIDIPFSHash); + output.println("421"); APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); - APIResponse.put("message", "Token Height not reached for corresponding Staked Tokens " + stakedToken); + APIResponse.put("message", "Consensus ID not unique"); IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); output.close(); input.close(); @@ -279,36 +282,15 @@ public static String receive() { return APIResponse.toString(); } - String senderToken = TokenDetails.toString(); - String consensusID = calculateHash(senderToken, "SHA3-256"); - writeToFile(LOGGER_PATH + "consensusID", consensusID, false); - String consensusIDIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "consensusID", ipfs); - deleteFile(LOGGER_PATH + "consensusID"); - - // if (!IPFSNetwork.dhtEmpty(consensusIDIPFSHash, ipfs)) { - // TokenReceiverLogger.debug("consensus ID not unique" + consensusIDIPFSHash); - // output.println("421"); - // APIResponse.put("did", senderDidIpfsHash); - // APIResponse.put("tid", "null"); - // APIResponse.put("status", "Failed"); - // APIResponse.put("message", "Consensus ID not unique"); - // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - // output.close(); - // input.close(); - // sk.close(); - // ss.close(); - // return APIResponse.toString(); - // } - // Check IPFS get for all Tokens int ipfsGetFlag = 0; - ArrayList allTokenContent = new ArrayList<>(); - ArrayList allTokenChainContent = new ArrayList<>(); + ArrayList wholeTokenContent = new ArrayList<>(); + ArrayList wholeTokenChainContent = new ArrayList<>(); for (int i = 0; i < intPart; i++) { String TokenChainContent = get(wholeTokenChains.getString(i), ipfs); - allTokenChainContent.add(TokenChainContent); + wholeTokenChainContent.add(TokenChainContent); String TokenContent = get(wholeTokens.getString(i), ipfs); - allTokenContent.add(TokenContent); + wholeTokenContent.add(TokenContent); ipfsGetFlag++; } repo(ipfs); @@ -395,6 +377,69 @@ public static String receive() { return APIResponse.toString(); } + boolean ownerCheck = true; + + JSONArray allTokens = new JSONArray(); + for (int i = 0; i < wholeTokens.length(); i++) + allTokens.put(wholeTokens.getString(i)); + for (int i = 0; i < partTokens.length(); i++) + allTokens.put(partTokens.getString(i)); + + JSONArray allTokensChains = new JSONArray(); + for (int i = 0; i < wholeTokenChainContent.size(); i++) + allTokensChains.put(wholeTokenChainContent.get(i)); + for (int i = 0; i < partTokenChainContent.length(); i++) + allTokensChains.put(partTokenChainContent.get(i)); + + JSONArray invalidTokens = new JSONArray(); + for (int i = 0; i < allTokensChains.length(); i++) { + JSONArray tokenChain = new JSONArray(allTokensChains.get(i).toString()); + JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); + TokenReceiverLogger.debug("Last Object = " + lastObject); + if (lastObject.has("owner")) { + TokenReceiverLogger.debug("Checking ownership"); + String owner = lastObject.getString("owner"); + String tokens = allTokens.getString(i); + String hashString = tokens.concat(senderDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + String ownerIdentity = hashForPositions.concat(positionsArray.getString(i)); + String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here Sender Calculation"); + TokenReceiverLogger.debug("tokens: " + tokens); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positionsArray.getString(i)); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); + + if (!owner.equals(ownerRecalculated)) { + ownerCheck = false; + invalidTokens.put(tokens); + } + } + + } + + if (!ownerCheck) { + TokenReceiverLogger.debug("Ownership Check Failed"); + String errorMessage = "Ownership Check Failed"; + output.println("424"); + output.println(invalidTokens.toString()); + 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 + TokenReceiverLogger.debug("Ownership Check Passed"); + boolean partsAvailable = true; for (int i = 0; i < partTokenChainContent.length(); i++) { Double senderCount = 0.000D, receiverCount = 0.000D; @@ -421,14 +466,12 @@ public static String receive() { if (availableParts > 1.000D) { TokenReceiverLogger.debug("Token wholly spent: " + partTokens.getString(i)); TokenReceiverLogger.debug("Parts: " + availableParts); + partsAvailable = false; } } - - String ownerIdentityHash; - JSONArray allTokens = new JSONArray(); if (!partsAvailable) { String errorMessage = "Token wholly spent already"; - output.println("424"); + output.println("425"); APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); @@ -440,27 +483,8 @@ public static String receive() { sk.close(); ss.close(); return APIResponse.toString(); - } else { - // Calculate Token Ownership - for (int i = 0; i < wholeTokens.length(); i++) - allTokens.put(wholeTokens.getString(i)); - for (int i = 0; i < partTokens.length(); i++) - allTokens.put(partTokens.getString(i)); - - String tokens = allTokens.toString(); - String hashString = tokens.concat(receiverDidIpfsHash); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - - String positions = getSignFromShares(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"), - hashForPositions); - - String ownerIdentity = receiverDidIpfsHash.concat(positions); - ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); - - output.println(ownerIdentityHash); - } - // output.println("200"); + output.println("200"); String senderDetails; try { @@ -485,15 +509,6 @@ public static String receive() { String comment = SenderDetails.getString("comment"); String Status = SenderDetails.getString("status"); String QuorumDetails = SenderDetails.getString("quorumsign"); - String ownerSigns = SenderDetails.getString("ownerSigns"); - - String hashForOwners = calculateHash(ownerSigns, "SHA3-256"); - BufferedImage pvt = ImageIO.read(new File(DATA_PATH.concat(receiverPeerID).concat("PrivateShare.png"))); - String firstPrivate = PropImage.img2bin(pvt); - int[] privateIntegerArray1 = strToIntArray(firstPrivate); - JSONObject positions = randomPositions("signer", hashForOwners, 32, privateIntegerArray1); - - String ownerIdentity = receiverDidIpfsHash.concat(positions.toString()); BufferedImage senderWidImage = ImageIO.read(new File(DATA_PATH + senderDidIpfsHash + "/PublicShare.png")); SenWalletBin = PropImage.img2bin(senderWidImage); @@ -592,7 +607,7 @@ public static String receive() { for (int i = 0; i < intPart; i++) { FileWriter fileWriter; fileWriter = new FileWriter(TOKENS_PATH + wholeTokens.getString(i)); - fileWriter.write(allTokenContent.get(i)); + fileWriter.write(wholeTokenContent.get(i)); fileWriter.close(); add(TOKENS_PATH + wholeTokens.getString(i), ipfs); pin(wholeTokens.getString(i), ipfs); @@ -635,8 +650,30 @@ public static String receive() { } long endTime = System.currentTimeMillis(); - for (int i = 0; i < intPart; i++) { + String tokens = wholeTokens.getString(i); + String hashString = tokens.concat(receiverDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + + BufferedImage pvt = ImageIO + .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(pvt); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + String ownerIdentity = hashForPositions.concat(positions); + String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here"); + TokenReceiverLogger.debug("tokens: " + wholeTokens.getString(i)); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positions); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); ArrayList groupTokens = new ArrayList<>(); for (int k = 0; k < intPart; k++) { @@ -648,14 +685,14 @@ public static String receive() { JSONObject objectToken = new JSONObject(); objectToken.put("tokenHash", wholeTokens.getString(i)); arrToken.put(objectToken); - JSONArray arr1 = new JSONArray(allTokenChainContent.get(i)); + JSONArray arr1 = new JSONArray(wholeTokenChainContent.get(i)); JSONObject obj2 = new JSONObject(); obj2.put("senderSign", senderSignature); obj2.put("sender", senderDidIpfsHash); obj2.put("group", groupTokens); obj2.put("comment", comment); obj2.put("tid", tid); - obj2.put("owner", ownerIdentity); + obj2.put("owner", ownerIdentityHash); arr1.put(obj2); writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); } @@ -674,6 +711,30 @@ public static String receive() { String chequeHash = IPFSNetwork.add(LOGGER_PATH.concat(partTokens.getString(i)), ipfs); deleteFile(LOGGER_PATH.concat(partTokens.getString(i))); + String tokens = partTokens.getString(i); + String hashString = tokens.concat(receiverDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + BufferedImage pvt = ImageIO + .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(pvt); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + + String ownerIdentity = hashForPositions.concat(positions); + String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here"); + TokenReceiverLogger.debug("tokens: " + partTokens.getString(i)); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positions); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); + JSONObject newPartObject = new JSONObject(); newPartObject.put("senderSign", senderSignature); newPartObject.put("sender", senderDidIpfsHash); @@ -681,7 +742,7 @@ public static String receive() { newPartObject.put("comment", comment); newPartObject.put("tid", tid); newPartObject.put("nextHash", ""); - newPartObject.put("owner", ownerIdentity); + newPartObject.put("owner", ownerIdentityHash); if (partTokenChainContent.getJSONArray(i).length() == 0) newPartObject.put("previousHash", ""); else diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 109d11cd..c32b7336 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -11,8 +11,6 @@ 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.correctPartToken; -import static com.rubix.Resources.Functions.correctToken; import static com.rubix.Resources.Functions.deleteFile; import static com.rubix.Resources.Functions.formatAmount; import static com.rubix.Resources.Functions.getCurrentUtcTime; @@ -26,6 +24,7 @@ import static com.rubix.Resources.Functions.readFile; import static com.rubix.Resources.Functions.sanityCheck; import static com.rubix.Resources.Functions.sanityMessage; +import static com.rubix.Resources.Functions.strToIntArray; import static com.rubix.Resources.Functions.syncDataTable; import static com.rubix.Resources.Functions.updateJSON; import static com.rubix.Resources.Functions.updateQuorum; @@ -38,6 +37,7 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import static com.rubix.Resources.IPFSNetwork.unpin; +import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; @@ -54,8 +54,10 @@ import java.util.Iterator; import java.util.List; +import javax.imageio.ImageIO; import javax.net.ssl.HttpsURLConnection; +import com.rubix.AuthenticateNode.PropImage; import com.rubix.Consensus.InitiatorConsensus; import com.rubix.Consensus.InitiatorProcedure; import com.rubix.Resources.Functions; @@ -168,6 +170,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } JSONArray wholeTokenChainHash = new JSONArray(); JSONArray tokenPreviousSender = new JSONArray(); + for (int i = 0; i < wholeTokens.length(); i++) { File token = new File(TOKENS_PATH + wholeTokens.get(i)); File tokenchain = new File(TOKENCHAIN_PATH + wholeTokens.get(i) + ".json"); @@ -199,6 +202,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception previousSenderObject.put("token", wholeTokenHash); previousSenderObject.put("sender", previousSenderArray); tokenPreviousSender.put(previousSenderObject); + } Double decimalAmount = requestedAmount - wholeAmount; @@ -349,6 +353,29 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception for (int i = 0; i < partTokens.length(); i++) allTokens.put(partTokens.getString(i)); + JSONArray positionsArray = new JSONArray(); + for (int i = 0; i < allTokens.length(); i++) { + String tokens = allTokens.getString(i); + String hashString = tokens.concat(senderDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + BufferedImage privateShare = ImageIO + .read(new File(DATA_PATH.concat(senderDidIpfsHash).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(privateShare); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + positionsArray.put(positions); + + TokenSenderLogger.debug("Ownership Here Sender Calculation"); + TokenSenderLogger.debug("tokens: " + tokens); + TokenSenderLogger.debug("hashString: " + hashString); + TokenSenderLogger.debug("hashForPositions: " + hashForPositions); + TokenSenderLogger.debug("p1: " + positions); + } + JSONArray alphaQuorum = new JSONArray(); JSONArray betaQuorum = new JSONArray(); JSONArray gammaQuorum = new JSONArray(); @@ -590,6 +617,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception JSONObject tokenObject = new JSONObject(); tokenObject.put("tokenDetails", tokenDetails); tokenObject.put("previousSender", tokenPreviousSender); + tokenObject.put("positions", positionsArray); tokenObject.put("amount", requestedAmount); tokenObject.put("amountLedger", amountLedger); @@ -602,6 +630,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String tokenAuth; try { tokenAuth = input.readLine(); + TokenSenderLogger.debug("Token Auth Code: " + tokenAuth); } catch (SocketException e) { TokenSenderLogger.warn("Receiver " + receiverDidIpfsHash + " is unable to Respond! - Token Auth"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); @@ -617,13 +646,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } - if (tokenAuth != null && (!tokenAuth.startsWith("4"))) { + if (tokenAuth != null && (tokenAuth.startsWith("4"))) { switch (tokenAuth) { case "420": String doubleSpent = input.readLine(); String owners = input.readLine(); JSONArray ownersArray = new JSONArray(owners); - correctToken(); TokenSenderLogger.info("Multiple Owners for " + doubleSpent); TokenSenderLogger.info("Owners " + ownersArray); TokenSenderLogger.info("Kindly re-initiate transaction"); @@ -631,30 +659,28 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception + ". Kindly re-initiate transaction"); break; case "421": - correctToken(); TokenSenderLogger.info("Consensus ID not unique. Kindly re-initiate transaction"); APIResponse.put("message", "Consensus ID not unique. Kindly re-initiate transaction"); break; case "422": - correctToken(); TokenSenderLogger.info("Tokens Not Verified. Kindly re-initiate transaction"); APIResponse.put("message", "Tokens Not Verified. Kindly re-initiate transaction"); break; case "423": - correctPartToken(); TokenSenderLogger.info("Broken Cheque Chain. Kindly re-initiate transaction"); APIResponse.put("message", "Broken Cheque Chain. Kindly re-initiate transaction"); break; case "424": - correctPartToken(); - TokenSenderLogger.info("Token wholly spent already. Kindly re-initiate transaction"); - APIResponse.put("message", "Token wholly spent already. Kindly re-initiate transaction"); + String invalidTokens = input.readLine(); + JSONArray tokensArray = new JSONArray(invalidTokens); + TokenSenderLogger.info("Ownership Check Failed for " + tokensArray); + APIResponse.put("message", "Ownership Check Failed"); break; + case "425": - correctToken(); - TokenSenderLogger.info("Stake incomplete for a selected token"); - APIResponse.put("message", "Stake incomplete for a selected token"); + TokenSenderLogger.info("Token wholly spent already. Kindly re-initiate transaction"); + APIResponse.put("message", "Token wholly spent already. Kindly re-initiate transaction"); break; } @@ -671,13 +697,13 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("status", "Failed"); return APIResponse; } + TokenSenderLogger.debug("Token Auth Code: " + tokenAuth); JSONObject dataObject = new JSONObject(); dataObject.put("tid", tid); dataObject.put("message", doubleSpendString); dataObject.put("receiverDidIpfs", receiverDidIpfsHash); dataObject.put("pvt", pvt); - dataObject.put("ownerIdentity", tokenAuth); dataObject.put("senderDidIpfs", senderDidIpfsHash); dataObject.put("token", wholeTokens.toString()); dataObject.put("alphaList", alphaPeersList); @@ -705,11 +731,9 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } - JSONArray ownerSigns = InitiatorConsensus.ownerSigns; TokenSenderLogger.debug("Consensus Reached"); senderDetails2Receiver.put("status", "Consensus Reached"); senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); - senderDetails2Receiver.put("ownerSigns", ownerSigns.toString()); output.println(senderDetails2Receiver); TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); From 1bb6adcea5ba2f7d6cc28a1c33974792503974fc Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 16 Mar 2022 16:23:02 +0530 Subject: [PATCH 019/179] var conts Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/InitiatorProcedure.java | 13 ++++++++----- src/com/rubix/Consensus/QuorumConsensus.java | 11 +++++++---- src/com/rubix/Constants/ConsensusConstants.java | 1 + 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorProcedure.java b/src/com/rubix/Consensus/InitiatorProcedure.java index 4b23b88e..63fdef30 100644 --- a/src/com/rubix/Consensus/InitiatorProcedure.java +++ b/src/com/rubix/Consensus/InitiatorProcedure.java @@ -1,5 +1,9 @@ package com.rubix.Consensus; +import static com.rubix.Constants.ConsensusConstants.HASH; +import static com.rubix.Constants.ConsensusConstants.INIT_HASH; +import static com.rubix.Constants.ConsensusConstants.RECEIVERID; +import static com.rubix.Constants.ConsensusConstants.TRANSACTION_ID; import static com.rubix.Resources.Functions.LOGGER_PATH; import static com.rubix.Resources.Functions.calculateHash; import static com.rubix.Resources.Functions.getSignFromShares; @@ -8,7 +12,6 @@ import java.io.IOException; -import com.rubix.Constants.ConsensusConstants; import com.rubix.SplitandStore.SeperateShares; import com.rubix.SplitandStore.Split; @@ -78,11 +81,11 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz senderSignQ = getSignFromShares(pvt, authSenderByQuorumHash); data1.put("sign", senderSignQ); data1.put("senderDID", senderDidIpfs); - data1.put("initHash", initHash()); + data1.put(INIT_HASH, initHash()); data1.put("token", token); - data1.put(ConsensusConstants.TRANSACTION_ID, tid); - data1.put(ConsensusConstants.HASH, authSenderByQuorumHash); - data1.put(ConsensusConstants.RECEIVERID, receiverDidIpfs); + data1.put(TRANSACTION_ID, tid); + data1.put(HASH, authSenderByQuorumHash); + data1.put(RECEIVERID, receiverDidIpfs); data2.put("Share1", Q1Share); data2.put("Share2", Q2Share); diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 8d532897..75975aed 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.HASH; +import static com.rubix.Constants.ConsensusConstants.RECEIVERID; +import static com.rubix.Constants.ConsensusConstants.TRANSACTION_ID; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; @@ -74,7 +77,7 @@ public void run() { while (true) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String peerID, transactionID, verifySenderHash, receiverDID, appName, senderPrivatePos, - senderDidIpfsHash = "", senderPID = "", ownerHash = ""; + senderDidIpfsHash = "", senderPID = "", ownerHash = "", initHash = "", token = ""; ServerSocket serverSocket = null; Socket socket = null; try { @@ -225,9 +228,9 @@ public void run() { readSenderData = new JSONObject(getRecData); senderPrivatePos = readSenderData.getString("sign"); senderDidIpfsHash = readSenderData.getString("senderDID"); - transactionID = readSenderData.getString("Tid"); - verifySenderHash = readSenderData.getString("Hash"); - receiverDID = readSenderData.getString("RID"); + transactionID = readSenderData.getString(TRANSACTION_ID); + verifySenderHash = readSenderData.getString(HASH); + receiverDID = readSenderData.getString(RECEIVERID); syncDataTable(senderDidIpfsHash, null); diff --git a/src/com/rubix/Constants/ConsensusConstants.java b/src/com/rubix/Constants/ConsensusConstants.java index 21a5a34a..1a76e6f8 100644 --- a/src/com/rubix/Constants/ConsensusConstants.java +++ b/src/com/rubix/Constants/ConsensusConstants.java @@ -5,6 +5,7 @@ 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 INIT_HASH = "initHash"; public static final String MINE_XORER = "yhevnyxcwblibeikfagmazsldzkfgnqwmketmcubnuvlbb"; } From dd4c2d2c608b226e986f3459d06c01abb40b21ae Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 17 Mar 2022 14:53:54 +0530 Subject: [PATCH 020/179] quorum consensus staking: recode Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 333 +++++++++++++++---- 1 file changed, 260 insertions(+), 73 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 75975aed..94e75246 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,19 +1,29 @@ package com.rubix.Consensus; -import static com.rubix.Constants.ConsensusConstants.HASH; -import static com.rubix.Constants.ConsensusConstants.RECEIVERID; -import static com.rubix.Constants.ConsensusConstants.TRANSACTION_ID; +import static com.rubix.Constants.ConsensusConstants.INIT_HASH; +import static com.rubix.Constants.MiningConstants.MINED_RBT; +import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; +import static com.rubix.Constants.MiningConstants.MINE_ID; +import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; +import static com.rubix.Constants.MiningConstants.MINE_TID; +import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; +import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; 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.PAYMENTS_PATH; 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.getPeerID; import static com.rubix.Resources.Functions.getSignFromShares; import static com.rubix.Resources.Functions.getValues; +import static com.rubix.Resources.Functions.initHash; 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; @@ -77,7 +87,7 @@ public void run() { while (true) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String peerID, transactionID, verifySenderHash, receiverDID, appName, senderPrivatePos, - senderDidIpfsHash = "", senderPID = "", ownerHash = "", initHash = "", token = ""; + senderDidIpfsHash = "", senderPID = "", ownerHash = "", initHash = ""; ServerSocket serverSocket = null; Socket socket = null; try { @@ -107,6 +117,174 @@ public void run() { serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } + + // ? staking logic starts here + + if (operation.equals("alpha-stake-token")) { + + QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); + String response = null; + + try { + + // ! token hash to be mined + response = in.readLine(); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - New Credits Details"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + + // ! check token is in same level and not already mined + if (response != null) { + + // valid mined token hash + + QuorumConsensusLogger.debug("Sending staking token details..."); + String mineID = null; + JSONArray tokenToStake = new JSONArray(); + + String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bankArray = new JSONArray(bankFile); + + // pick last object from bank array + JSONObject bankObject = bankArray.getJSONObject(0); + String tokenHash = bankObject.getString("tokenHash"); + tokenToStake.put(tokenHash); + + File tokenFile = new File(TOKENS_PATH + tokenHash); + File tokenchainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); + + if (tokenFile.exists() && tokenchainFile.exists()) { + + String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); + tokenToStake.put(tokenChain); + + // ! token which will be staked + out.println(tokenToStake); + } else { + QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); + out.println("445"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + + // ! mine details to sign + JSONObject mineDetToSign = new JSONObject(); + + try { + String mineData = in.readLine(); + // convert mineData to JSONObject + mineDetToSign = new JSONObject(mineData); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - Stake ID details (to be signed)"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + + if (mineDetToSign.length() == 3 && mineDetToSign.has( + MINE_ID) && mineDetToSign.has( + MINED_RBT) + && mineDetToSign.has(MINE_TID)) { + JSONObject stakingSigns = new JSONObject(); + + QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); + + stakingSigns.put( + STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + tokenHash)); + stakingSigns.put( + MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + mineDetToSign.getString(MINE_TID))); + stakingSigns.put( + MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + mineDetToSign.getString(MINED_RBT))); + stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + mineDetToSign.getString(MINE_ID))); + + out.println(stakingSigns.toString()); + } else { + QuorumConsensusLogger.debug("Incorrect stake details"); + out.println("445"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + + // ! receive credits equal to credits required to mine token + + String credits = null; + try { + credits = in.readLine(); + // convert mineData to JSONObject + System.out.println("credits received " + credits); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - Adding Credits Failed"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + + JSONArray creditArray = new JSONArray(credits); + + // Get level of token from advisory node + int creditsRequired = 0; + JSONObject resJsonData_credit = new JSONObject(); + String GET_URL_credit = SYNC_IP + "/getlevel"; + URL URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + QuorumConsensusLogger.debug("response from service " + response_credit.toString()); + resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + creditsRequired = (int) Math.pow(2, (2 + level_credit)); + QuorumConsensusLogger.debug("credits required " + creditsRequired); + + } else + QuorumConsensusLogger.debug("GET request not worked"); + + if ((creditArray.length() != creditsRequired) && (creditsRequired != 0)) { + + QuorumConsensusLogger.debug("Credits not received"); + out.println("446"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } else { + QuorumConsensusLogger.debug("Credits received"); + out.println("200"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + + // ! store the credits + + } + + } else { + out.println("444"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + } + + // ? staking logic ends here + if (operation.equals("new-credits-mining")) { QuorumConsensusLogger.debug("New Credits"); String getNewCreditsData = null; @@ -121,86 +299,95 @@ public void run() { // Verify QST Credits JSONObject qstObject = new JSONObject(getNewCreditsData); - // Get level of token from advisory node - int creditsRequired = 0; - JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getlevel"; - URL URLobj_credit = new URL(GET_URL_credit); - HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); - con_credit.setRequestMethod("GET"); - int responseCode_credit = con_credit.getResponseCode(); - System.out.println("GET Response Code :: " + responseCode_credit); - if (responseCode_credit == HttpURLConnection.HTTP_OK) { - BufferedReader in_credit = new BufferedReader( - new InputStreamReader(con_credit.getInputStream())); - String inputLine_credit; - StringBuffer response_credit = new StringBuffer(); - while ((inputLine_credit = in_credit.readLine()) != null) { - response_credit.append(inputLine_credit); - } - in_credit.close(); - QuorumConsensusLogger.debug("response from service " + response_credit.toString()); - resJsonData_credit = new JSONObject(response_credit.toString()); - int level_credit = resJsonData_credit.getInt("level"); - creditsRequired = (int) Math.pow(2, (2 + level_credit)); - QuorumConsensusLogger.debug("credits required " + creditsRequired); - - } else - QuorumConsensusLogger.debug("GET request not worked"); - - // Level 1 Verification: Verify hash of n objects - JSONArray qstArray = qstObject.getJSONArray("qstArray"); - JSONArray creditsArray = qstObject.getJSONArray("credits"); - - boolean flag = true; - for (int i = 0; i < creditsRequired; i++) { - QuorumConsensusLogger.debug("Credit object: " + creditsArray.getJSONObject(i).toString()); - QuorumConsensusLogger.debug( - "Credit Hash: " + calculateHash(creditsArray.getJSONObject(i).toString(), "SHA3-256")); - String reHash = calculateHash(qstArray.getJSONObject(i).getString("credits"), "SHA3-256"); - if (!reHash.equals(qstArray.getJSONObject(i).getString("creditHash"))) { - QuorumConsensusLogger.debug("Recalculation " + reHash + " - " - + qstArray.getJSONObject(i).getString("creditHash")); - flag = false; - } - } - if (flag) { + if (qstObject.getString(INIT_HASH) == initHash()) { + + // Get level of token from advisory node + int creditsRequired = 0; + JSONObject resJsonData_credit = new JSONObject(); + String GET_URL_credit = SYNC_IP + "/getlevel"; + URL URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + QuorumConsensusLogger.debug("response from service " + response_credit.toString()); + resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + creditsRequired = (int) Math.pow(2, (2 + level_credit)); + QuorumConsensusLogger.debug("credits required " + creditsRequired); + + } else + QuorumConsensusLogger.debug("GET request not worked"); - boolean verifySigns = true; + // Level 1 Verification: Verify hash of n objects + JSONArray qstArray = qstObject.getJSONArray("qstArray"); + JSONArray creditsArray = qstObject.getJSONArray("credits"); + + boolean flag = true; for (int i = 0; i < creditsRequired; i++) { - if (!Authenticate.verifySignature(creditsArray.getJSONObject(i).toString())) - verifySigns = false; + QuorumConsensusLogger.debug("Credit object: " + creditsArray.getJSONObject(i).toString()); + QuorumConsensusLogger.debug( + "Credit Hash: " + + calculateHash(creditsArray.getJSONObject(i).toString(), "SHA3-256")); + String reHash = calculateHash(qstArray.getJSONObject(i).getString("credits"), "SHA3-256"); + if (!reHash.equals(qstArray.getJSONObject(i).getString("creditHash"))) { + QuorumConsensusLogger.debug("Recalculation " + reHash + " - " + + qstArray.getJSONObject(i).getString("creditHash")); + flag = false; + } } - if (verifySigns) { - HashSet hashSet = new HashSet(); - long startTime = System.currentTimeMillis(); - for (int i = 0; i < creditsArray.length(); i++) { - String sign = creditsArray.getJSONObject(i).getString("signature"); - String signHash = calculateHash(sign, "SHA3-256"); - hashSet.add(signHash); + if (flag) { + + boolean verifySigns = true; + for (int i = 0; i < creditsRequired; i++) { + if (!Authenticate.verifySignature(creditsArray.getJSONObject(i).toString())) + verifySigns = false; } - long endTime = System.currentTimeMillis(); - QuorumConsensusLogger.debug("Total Time for HashSet: " + (endTime - startTime)); - if (hashSet.size() == qstArray.length() * 15) { - QuorumConsensusLogger.debug("Mining Verified"); - out.println("Verified"); + if (verifySigns) { + HashSet hashSet = new HashSet(); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < creditsArray.length(); i++) { + String sign = creditsArray.getJSONObject(i).getString("signature"); + String signHash = calculateHash(sign, "SHA3-256"); + hashSet.add(signHash); + } + long endTime = System.currentTimeMillis(); + QuorumConsensusLogger.debug("Total Time for HashSet: " + (endTime - startTime)); + if (hashSet.size() == qstArray.length() * 15) { + QuorumConsensusLogger.debug("Mining Verified"); + out.println("Verified"); + } else { + QuorumConsensusLogger + .debug("HashSet: " + hashSet.size() + " QST Size " + qstArray.length()); + QuorumConsensusLogger.debug("Mining Not Verified: Duplicates Found"); + out.println("440"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } } else { - QuorumConsensusLogger - .debug("HashSet: " + hashSet.size() + " QST Size " + qstArray.length()); - QuorumConsensusLogger.debug("Mining Not Verified: Duplicates Found"); - out.println("440"); + out.println("441"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } } else { - out.println("441"); + out.println("442"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } } else { - out.println("442"); + out.println("443"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); @@ -228,9 +415,10 @@ public void run() { readSenderData = new JSONObject(getRecData); senderPrivatePos = readSenderData.getString("sign"); senderDidIpfsHash = readSenderData.getString("senderDID"); - transactionID = readSenderData.getString(TRANSACTION_ID); - verifySenderHash = readSenderData.getString(HASH); - receiverDID = readSenderData.getString(RECEIVERID); + transactionID = readSenderData.getString("Tid"); + verifySenderHash = readSenderData.getString("Hash"); + receiverDID = readSenderData.getString("RID"); + initHash = readSenderData.getString(INIT_HASH); syncDataTable(senderDidIpfsHash, null); @@ -276,7 +464,6 @@ public void run() { if (!creditSignatures.equals("null")) { // commented as per test for multiple consensus // threads - FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); shareWriter.write(creditSignatures); shareWriter.close(); From 2afc5c35978149ee6bfdc241592bff8813bfb984 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 18 Mar 2022 21:54:40 +0530 Subject: [PATCH 021/179] stake module - initiate 1/ Signed-off-by: Nidhin Mahesh A --- .idea/libraries/java_cid_v1_1_0.xml | 20 ++ java-rubix-core.iml | 2 +- .../rubix/AuthenticateNode/SplitShares.java | 15 +- .../rubix/Consensus/InitiatorConsensus.java | 282 +----------------- .../rubix/Consensus/InitiatorProcedure.java | 15 +- src/com/rubix/Consensus/QuorumConsensus.java | 14 +- src/com/rubix/Consensus/StakeConsensus.java | 102 +++++++ src/com/rubix/Mining/ProofCredits.java | 46 ++- src/com/rubix/Ping/PingCheck.java | 31 +- src/com/rubix/Resources/APIHandler.java | 1 - src/com/rubix/Resources/Functions.java | 121 ++------ src/com/rubix/Resources/IPFSNetwork.java | 12 - 12 files changed, 249 insertions(+), 412 deletions(-) create mode 100644 .idea/libraries/java_cid_v1_1_0.xml create mode 100644 src/com/rubix/Consensus/StakeConsensus.java diff --git a/.idea/libraries/java_cid_v1_1_0.xml b/.idea/libraries/java_cid_v1_1_0.xml new file mode 100644 index 00000000..c5d600c5 --- /dev/null +++ b/.idea/libraries/java_cid_v1_1_0.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/java-rubix-core.iml b/java-rubix-core.iml index d9323fbd..1c205d42 100644 --- a/java-rubix-core.iml +++ b/java-rubix-core.iml @@ -8,6 +8,6 @@ - + \ No newline at end of file diff --git a/src/com/rubix/AuthenticateNode/SplitShares.java b/src/com/rubix/AuthenticateNode/SplitShares.java index 4f0897f9..1ba367c0 100644 --- a/src/com/rubix/AuthenticateNode/SplitShares.java +++ b/src/com/rubix/AuthenticateNode/SplitShares.java @@ -1,15 +1,16 @@ package com.rubix.AuthenticateNode; -import static com.rubix.Resources.Functions.IPFS_PORT; + +import io.ipfs.api.IPFS; +import org.apache.log4j.Logger; +import org.json.JSONArray; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; -import org.apache.log4j.Logger; -import org.json.JSONArray; +import static com.rubix.Resources.Functions.IPFS_PORT; -import io.ipfs.api.IPFS; public class SplitShares { public static Logger SplitSharesLogger = Logger.getLogger(SplitShares.class); @@ -19,9 +20,9 @@ public class SplitShares { public static JSONArray initiate; static JSONArray arr = new JSONArray(); + /** - * This is the main method to be called for converting the secret into binary - * and creating shares + * This is the main method to be called for converting the secret into binary and creating shares * * @param decentralizedID Secret string * @return Array of shares @@ -35,3 +36,5 @@ private static boolean generateShares(BufferedImage decentralizedID) throws IOEx } } + + diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index 35018f78..c14667d6 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -1,36 +1,19 @@ package com.rubix.Consensus; -import static com.rubix.Constants.MiningConstants.MINED_RBT; -import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; -import static com.rubix.Constants.MiningConstants.MINE_ID; -import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; -import static com.rubix.Constants.MiningConstants.MINE_TID; -import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; -import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; -import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; -import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; +import static com.rubix.Constants.ConsensusConstants.INIT_HASH; 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.WALLET_DATA_PATH; -import static com.rubix.Resources.Functions.checkTokenOwnershiByDID; -import static com.rubix.Resources.Functions.deleteFile; import static com.rubix.Resources.Functions.getValues; -import static com.rubix.Resources.Functions.levelHeight; +import static com.rubix.Resources.Functions.initHash; import static com.rubix.Resources.Functions.minQuorum; import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.Functions.syncDataTable; -import static com.rubix.Resources.Functions.writeToFile; -import static com.rubix.Resources.IPFSNetwork.add; import static com.rubix.Resources.IPFSNetwork.forward; -import static com.rubix.Resources.IPFSNetwork.getMineID; -import static com.rubix.Resources.IPFSNetwork.pin; import static com.rubix.Resources.IPFSNetwork.repo; import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import java.io.BufferedReader; -import java.io.File; -import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; @@ -54,20 +37,12 @@ public class InitiatorConsensus { public static Logger InitiatorConsensusLogger = Logger.getLogger(InitiatorConsensus.class); public static volatile JSONObject quorumSignature = new JSONObject(); - public static volatile JSONObject stakingSignature = new JSONObject(); + public static volatile JSONArray signedAphaQuorumArray = new JSONArray(); 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 boolean stakeComplete = false; public static volatile JSONArray finalQuorumSignsArray = new JSONArray(); - public static JSONArray ownerSigns = new JSONArray(); - private static int levelHeightValue; - - /** - * Added by Anuradha K on 04/01/20222. - * To address SocketConnection reset Issue - */ private static int socketTimeOut = 120000; /** @@ -90,28 +65,6 @@ private static synchronized boolean voteNCount(int i, int quorumSize) { return status; } - /** - * This method increments the quorumResponse variable - */ - // private static synchronized boolean stakingQuorumExists(int i) { - // boolean status; - // PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - // synchronized (stakeLock) { - // if (signedAlphaQuorumID[i] < 1) { - // quorumResponse[i]++; - // InitiatorConsensusLogger - // .debug("quorum response for staking added index " + i + " is " + - // quorumResponse[i] - // + " quorumsize "); - // status = false; - // } else { - // status = true; - // InitiatorConsensusLogger.debug("Staking Reached for index " + i); - // } - // } - // return status; - // } - /** * This method stores all the quorum signatures until required count for * consensus @@ -158,7 +111,6 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri PrintStream[] qOut = new PrintStream[QUORUM_COUNT]; BufferedReader[] qIn = new BufferedReader[QUORUM_COUNT]; String[] quorumID = new String[QUORUM_COUNT]; - String[] signedAlphaQuorumPID = new String[7]; PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); JSONObject dataObject = new JSONObject(data); String hash = dataObject.getString("hash"); @@ -190,7 +142,6 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri 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); @@ -208,9 +159,9 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri qOut[j].println(operation); if (operation.equals("new-credits-mining")) { - - // ? QST + credit info JSONObject qstDetails = dataObject.getJSONObject("qstDetails"); + qstDetails.put(INIT_HASH, initHash()); + // Verify QST Credits qOut[j].println(qstDetails.toString()); try { qResponse[j] = qIn[j].readLine(); @@ -220,7 +171,6 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri } if (qResponse[j] != null) { if (qResponse[j].equals("Verified")) { - qOut[j].println(detailsToken); try { qResponse[j] = qIn[j].readLine(); @@ -233,9 +183,8 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (qResponse[j].equals("Auth_Failed")) { IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } else { - InitiatorConsensusLogger.trace( - "Signature Received from Q" + j + "(" + quorumID[j] + ") : " - + qResponse[j]); + InitiatorConsensusLogger.debug( + "Signature Received from " + quorumID[j] + " " + qResponse[j]); if (quorumResponse[index] > minQuorum(quorumSize)) { qOut[j].println("null"); IPFSNetwork @@ -289,27 +238,6 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri } } - try { - qResponse[j] = qIn[j].readLine(); - } catch (SocketException e) { - InitiatorConsensusLogger - .warn("Quorum " + quorumID[j] + " is unable to Respond!"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); - } - - if (qResponse[j] != null) { - if (qResponse[j].equals("Auth_Failed")) { - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); - } else { - JSONObject signObject = new JSONObject(); - signObject.put("did", quorumID[j]); - signObject.put("hash", detailsToken.getString("ownerIdentity")); - signObject.put("signature", qResponse[j]); - ownerSigns.put(signObject); - - } - } - } else if (qResponse[j].equals("440")) { InitiatorConsensusLogger.debug("Credit Verification failed: Duplicates found"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); @@ -321,10 +249,11 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri InitiatorConsensusLogger.debug("Credit Verification failed: Credits hash mismatch"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } else if (qResponse[j].equals("443")) { - InitiatorConsensusLogger.debug("Failed to Initialize Credit Verification"); + InitiatorConsensusLogger.debug("Credit Verification failed: Init hash mismatch"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); } } + } qOut[j].println(detailsToken); @@ -352,18 +281,16 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri JSONObject detailsToVerify = new JSONObject(); detailsToVerify.put("did", didHash); detailsToVerify.put("hash", hash); - detailsToVerify.put("signatures", qResponse[j]); + detailsToVerify.put("signature", qResponse[j]); if (Authenticate.verifySignature(detailsToVerify.toString())) { InitiatorConsensusLogger.debug(role + " node authenticated at index " + index); boolean voteStatus = voteNCount(index, quorumSize); if (quorumResponse[index] <= minQuorum(quorumSize) && voteStatus) { - - if (j <= 7) { - signedAlphaQuorumPID[j] = quorumID[j]; - } - InitiatorConsensusLogger .debug("waiting for " + quorumSize + " +signs " + role); + if (role.equals("alpha")) { + signedAphaQuorumArray.put(quorumID[j]); + } while (quorumResponse[index] < minQuorum(quorumSize)) { } InitiatorConsensusLogger @@ -393,7 +320,6 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri } } } - } catch (IOException | JSONException e) { IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[j]); InitiatorConsensusLogger.error("IOException Occurred"); @@ -403,188 +329,6 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri quorumThreads[j].start(); } - if (operation.equals("new-credits-mining")) { - - levelHeightValue = levelHeight(); - - Thread[] stakingThreads = new Thread[signedAlphaQuorumPID.length]; - - // choosing a quorum member from 1 to 5 who have signed the transaction - for (int p = 0; p < signedAlphaQuorumPID.length; p++) { - int s = p; - stakingThreads[p] = new Thread(() -> { - try { - if (signedAlphaQuorumPID[s] != null) { - InitiatorConsensusLogger.debug( - "Contacting Signed Alpha Quorum Peer : " + signedAlphaQuorumPID[s] - + " for staking. Index: " + s); - - qSocket[s] = new Socket("127.0.0.1", PORT + s); - qSocket[s].setSoTimeout(socketTimeOut); - qIn[s] = new BufferedReader(new InputStreamReader(qSocket[s].getInputStream())); - qOut[s] = new PrintStream(qSocket[s].getOutputStream()); - - qOut[s].println("stake-token"); - try { - - qResponse[s] = qIn[s].readLine(); - // convert to JSON array - JSONArray stakingTokenDetals = new JSONArray(qResponse[s]); - // get token chain and token ID from the array - String stakingTokenHash = stakingTokenDetals.getString(0); - JSONArray stakingTokenChain = stakingTokenDetals.getJSONArray(1); - - String stakingQuorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", - "peerid", signedAlphaQuorumPID[s]); - if (checkTokenOwnershiByDID(stakingTokenHash, stakingQuorumDID) - && stakingTokenChain.length() > levelHeightValue) { - - InitiatorConsensusLogger.debug("Staking Token Received and Verified from " - + signedAlphaQuorumPID[s] + " " + qResponse[s]); - - String mineID = getMineID(stakingTokenHash, ipfs); - InitiatorConsensusLogger - .debug("Sending mine ID to miner :" + mineID); - JSONObject detToSign = new JSONObject(); - detToSign.put(MINE_ID, mineID); - detToSign.put(MINE_TID, detailsToken.getString("Tid")); - detToSign.put(MINED_RBT, detailsToken.getString("token")); - qOut[s].println(detToSign.toString()); - - JSONObject stakingQuorumSigned = new JSONObject(); - - try { - qResponse[s] = qIn[s].readLine(); - // convert to JSON array - stakingQuorumSigned = new JSONObject(qResponse[s]); - InitiatorConsensusLogger.debug("Signature for Mining ID Received from " - + signedAlphaQuorumPID[s] + " " + qResponse[s]); - } catch (SocketException e) { - InitiatorConsensusLogger - .warn("Quorum " + quorumID[s] + " is unable to Respond!"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); - } - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakingQuorumDID); - detailsToVerify.put("hash", mineID); - detailsToVerify.put("signature", stakingQuorumSigned.getString(MINE_ID_SIGN)); - - if (Authenticate.verifySignature(detailsToVerify.toString())) { - - stakingSignature.put(MINE_TID, detailsToken.getString("Tid")); - stakingSignature.put(MINED_RBT, detailsToken.getString("token")); - stakingSignature.put(MINE_ID, mineID); - stakingSignature.put(STAKED_QUORUM_DID, stakingQuorumDID); - stakingSignature.put(STAKED_TOKEN, stakingTokenHash); - - stakingSignature.put(STAKED_TOKEN_SIGN, stakingQuorumSigned.getString( - STAKED_TOKEN_SIGN)); - stakingSignature.put(MINING_TID_SIGN, stakingQuorumSigned.getString( - MINING_TID_SIGN)); - stakingSignature.put(MINED_RBT_SIGN, stakingQuorumSigned.getString( - MINED_RBT_SIGN)); - stakingSignature.put(MINE_ID_SIGN, - stakingQuorumSigned.getString(MINE_ID_SIGN)); - - if (!stakeComplete) { - FileWriter shareWriter = new FileWriter( - new File(LOGGER_PATH + "mineID.txt"), - true); - shareWriter.write(detailsToVerify.toString(0)); - shareWriter.close(); - File readMineID = new File(LOGGER_PATH + "mineID.txt"); - String mineData = add(readMineID.toString(), ipfs); - pin(mineData, ipfs); - - File mineIDFile = new File( - WALLET_DATA_PATH.concat("/Stakes/").concat(mineData) - .concat(".json")); - if (!mineIDFile.exists()) - mineIDFile.createNewFile(); - writeToFile(mineIDFile.toString(), qResponse[s], false); - - InitiatorConsensusLogger.debug("Mine object: " + mineData); - deleteFile(LOGGER_PATH + "mineID.txt"); - - InitiatorConsensusLogger.debug("Staking Successful at index " + s); - - IPFSNetwork - .executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID[s]); - - JSONObject stakingInfo = new JSONObject(); - stakingInfo.put("StakerDID", stakingQuorumDID); - stakingInfo.put("StakedokenID", stakingTokenHash); - stakingInfo.put("minedToken", detailsToken); - - JSONArray creditArray = new JSONArray(); - - InitiatorConsensusLogger.debug("Staking Successful at index " + s); - InitiatorConsensusLogger - .debug("Sending Credits to DID: " + stakingQuorumDID); - - for (int i = 0; i < levelHeightValue; i++) { - - creditArray.put(finalQuorumSignsArray); - } - - qOut[s].println(creditArray); - - stakeComplete = true; - } else { - - InitiatorConsensusLogger.debug("sending null for slow quorum"); - qOut[s].println("null"); - IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); - } - - } else { - - InitiatorConsensusLogger.debug("sending null for slow quorum"); - qOut[s].println("null"); - IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); - - } - - } else { - - InitiatorConsensusLogger.debug("sending null for slow quorum "); - qOut[s].println("null"); - IPFSNetwork.executeIPFSCommands( - "ipfs p2p close -t /p2p/" + signedAlphaQuorumPID[s]); - - } - } catch (SocketException e) { - InitiatorConsensusLogger - .warn("Alpha Quorum (for Staking)" + signedAlphaQuorumPID[s] - + " is unable to Respond!"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + - signedAlphaQuorumPID[s]); - } - } - - } catch (Exception e) { - InitiatorConsensusLogger.error("Exception Occurred"); - e.printStackTrace(); - } - }); - stakingThreads[s].start(); - } - // check the balance - // if balance is sufficient then stake the token - // else send a null to Qa(j) - // if Qa(j) sends a null then close the connection - // else send the stake ID to Qa(j) - // pin the stake ID (initiator) and keep it in a file for future use - File stakesFolder = new File(WALLET_DATA_PATH.concat("/Stakes")); - if (!stakesFolder.exists()) - stakesFolder.mkdirs(); - // send mining fee to Qa(j) - 0.02 RBT - // close the connection - } - while (quorumResponse[index] < minQuorum(quorumSize) || quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { } diff --git a/src/com/rubix/Consensus/InitiatorProcedure.java b/src/com/rubix/Consensus/InitiatorProcedure.java index 63fdef30..0a2cc5b9 100644 --- a/src/com/rubix/Consensus/InitiatorProcedure.java +++ b/src/com/rubix/Consensus/InitiatorProcedure.java @@ -1,9 +1,5 @@ package com.rubix.Consensus; -import static com.rubix.Constants.ConsensusConstants.HASH; -import static com.rubix.Constants.ConsensusConstants.INIT_HASH; -import static com.rubix.Constants.ConsensusConstants.RECEIVERID; -import static com.rubix.Constants.ConsensusConstants.TRANSACTION_ID; import static com.rubix.Resources.Functions.LOGGER_PATH; import static com.rubix.Resources.Functions.calculateHash; import static com.rubix.Resources.Functions.getSignFromShares; @@ -12,6 +8,7 @@ import java.io.IOException; +import com.rubix.Constants.ConsensusConstants; import com.rubix.SplitandStore.SeperateShares; import com.rubix.SplitandStore.Split; @@ -37,6 +34,7 @@ public class InitiatorProcedure { * @param data Data required for hashing and signing * @param ipfs IPFS instance * @param PORT port for forwarding to quorum + * @throws IOException */ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSize, String operation) throws JSONException { @@ -81,11 +79,10 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz senderSignQ = getSignFromShares(pvt, authSenderByQuorumHash); data1.put("sign", senderSignQ); data1.put("senderDID", senderDidIpfs); - data1.put(INIT_HASH, initHash()); - data1.put("token", token); - data1.put(TRANSACTION_ID, tid); - data1.put(HASH, authSenderByQuorumHash); - data1.put(RECEIVERID, receiverDidIpfs); + data1.put(ConsensusConstants.TRANSACTION_ID, tid); + data1.put(ConsensusConstants.HASH, authSenderByQuorumHash); + data1.put(ConsensusConstants.RECEIVERID, receiverDidIpfs); + data1.put(ConsensusConstants.INIT_HASH, initHash()); data2.put("Share1", Q1Share); data2.put("Share2", Q2Share); diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 94e75246..6559342a 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -126,8 +126,7 @@ public void run() { String response = null; try { - - // ! token hash to be mined + // ! token hash just mined response = in.readLine(); } catch (SocketException e) { QuorumConsensusLogger.debug("Sender Input Stream Null - New Credits Details"); @@ -136,13 +135,16 @@ public void run() { executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - // ! check token is in same level and not already mined - if (response != null) { + QuorumConsensusLogger.debug("Validating new token details..."); + + boolean isValid = false; + + // ! check token is in same level + // ! validate mined token hash and ownership - // valid mined token hash + if (isValid) { QuorumConsensusLogger.debug("Sending staking token details..."); - String mineID = null; JSONArray tokenToStake = new JSONArray(); String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java new file mode 100644 index 00000000..e0ce4dc6 --- /dev/null +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -0,0 +1,102 @@ +package com.rubix.Consensus; + +import static com.rubix.Resources.Functions.DATA_PATH; +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.syncDataTable; +import static com.rubix.Resources.IPFSNetwork.forward; +import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.Socket; +import java.net.SocketException; + +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 StakeConsensus { + public static Logger StakeConsensusLogger = Logger.getLogger(StakeConsensus.class); + private static int socketTimeOut = 120000; + public static volatile JSONObject stakeDetails = new JSONObject(); + // mine ID + // QST_Height + // staker DID + // staked token hash + // sign on staking token + // sign on txn id + // sign on mining token + // same object will be added to tokenchains of staked and mined token + + public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject data, IPFS ipfs, int PORT, + String operation) { + + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + String[] qResponse = new String[signedAphaQuorumArray.length()]; + Socket[] qSocket = new Socket[signedAphaQuorumArray.length()]; + PrintStream[] qOut = new PrintStream[signedAphaQuorumArray.length()]; + BufferedReader[] qIn = new BufferedReader[signedAphaQuorumArray.length()]; + String[] quorumID = new String[signedAphaQuorumArray.length()]; + + try { + + for (int j = 0; j < signedAphaQuorumArray.length(); j++) + quorumID[j] = signedAphaQuorumArray.getString(j); + + Thread[] quorumThreads = new Thread[signedAphaQuorumArray.length()]; + for (int i = 0; i < signedAphaQuorumArray.length(); i++) { + int j = i; + quorumThreads[i] = new Thread(() -> { + try { + 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("alpha"); + StakeConsensusLogger.debug("quourm ID " + quorumID[j] + " appname " + appName); + forward(appName, PORT + j, quorumID[j]); + StakeConsensusLogger.debug( + "Connected to " + quorumID[j] + "on port " + (PORT + j) + "with AppName" + appName); + + qSocket[j] = new Socket("127.0.0.1", PORT + j); + qSocket[j].setSoTimeout(socketTimeOut); + qIn[j] = new BufferedReader(new InputStreamReader(qSocket[j].getInputStream())); + qOut[j] = new PrintStream(qSocket[j].getOutputStream()); + + qOut[j].println(operation); + if (operation.equals("alpha-stake-token")) { + + qOut[j].println(data.toString()); + StakeConsensusLogger.debug("Token Details sent for validation..."); + + try { + qIn[j].readLine(); + StakeConsensusLogger.debug("Token Details validated. Received stake token details.."); + } catch (SocketException e) { + + } + + } + + } catch (Exception e) { + StakeConsensusLogger.error("Error in quorum consensus thread: " + e); + } + }); + } + ; + + } catch (Exception e) { + StakeConsensusLogger.error("Error in getStakeConsensus: " + e); + } + } + +} diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 3ecfdfa0..705f5bfc 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -48,6 +48,7 @@ import com.rubix.AuthenticateNode.PropImage; import com.rubix.Consensus.InitiatorConsensus; import com.rubix.Consensus.InitiatorProcedure; +import com.rubix.Consensus.StakeConsensus; import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; @@ -76,6 +77,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON int type = detailsObject.getInt("type"); int creditUsed = 0; long totalTime = 0; + int QSTHeight = 0; JSONArray alphaQuorum = new JSONArray(); JSONArray betaQuorum = new JSONArray(); @@ -90,6 +92,17 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONArray newQstArray = new JSONArray(readFile(WALLET_DATA_PATH + "QuorumSignedTransactions.json")); int availableCredits = newQstArray.length(); + File minedCH = new File(WALLET_DATA_PATH + "MinedCreditsHistory.json"); + if (!minedCH.exists()) { + minedCH.createNewFile(); + writeToFile(WALLET_DATA_PATH + "MinedCreditsHistory.json", "[]", false); + } + String creditsHistory = readFile(WALLET_DATA_PATH + "MinedCreditsHistory.json"); + JSONArray creditsHistoryArray = new JSONArray(creditsHistory); + + // ! get actual qst height for current scenario + QSTHeight = availableCredits + creditsHistoryArray.length(); + ProofCreditsLogger.debug("Credits available: " + availableCredits); String GET_URL_credit = SYNC_IP + "/getlevel"; URL URLobj_credit = new URL(GET_URL_credit); @@ -340,6 +353,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } } } + JSONObject stakingData = new JSONObject(); for (int i = 0; i < token.length(); i++) { writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); @@ -379,6 +393,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.debug("hashString: " + hashString); ProofCreditsLogger.debug("hashForPositions: " + hashForPositions); ProofCreditsLogger.debug("p1: " + positions); + ProofCreditsLogger.debug("QSTHeight: " + QSTHeight); ProofCreditsLogger.debug("ownerIdentity: " + ownerIdentity); ProofCreditsLogger.debug("ownerIdentityHash: " + ownerIdentityHash); JSONArray tokenChainArray = new JSONArray(); @@ -389,8 +404,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject.put("tid", tid); tokenChainGenesisObject.put("owner", ownerIdentityHash); tokenChainGenesisObject.put("blockNumber", 0); + tokenChainGenesisObject.put("QSTHeight", QSTHeight); tokenChainGenesisObject.put("nextHash", calculateHash(tid, "SHA3-256")); tokenChainGenesisObject.put("previousHash", ""); + stakingData = tokenChainGenesisObject; tokenChainArray.put(tokenChainGenesisObject); writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); @@ -401,13 +418,30 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON updateJSON("add", PAYMENTS_PATH + "BNK00.json", tempArray.toString()); } - File minedCH = new File(WALLET_DATA_PATH + "MinedCreditsHistory.json"); - if (!minedCH.exists()) { - minedCH.createNewFile(); - writeToFile(WALLET_DATA_PATH + "MinedCreditsHistory.json", "[]", false); + // ! new token will now need a staked token + StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, + stakingData, ipfs, SEND_PORT + 3, + "alpha-stake-token"); + + if (!(InitiatorConsensus.quorumSignature.length() >= 3 * minQuorum(7))) { + APIResponse.put("did", DID); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Consensus failed"); + ProofCreditsLogger.debug("consensus failed"); + } else { + ProofCreditsLogger.debug("token mined " + token); + + int counter = 0; + + for (int i = 0; i < availableCredits; i++) { + JSONObject temp = newQstArray.getJSONObject(i); + if (counter < creditUsed) { + prooftid.put(temp.getString("tid")); + counter++; + } + } } - String creditsHistory = readFile(WALLET_DATA_PATH + "MinedCreditsHistory.json"); - JSONArray creditsHistoryArray = new JSONArray(creditsHistory); for (int i = 0; i < creditUsed; i++) { JSONObject minedObject = new JSONObject(); minedObject.put("tid", newQstArray.getJSONObject(i).getString("tid")); diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index c8f8ef1e..87e0a2cb 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -1,25 +1,35 @@ package com.rubix.Ping; -import io.ipfs.api.IPFS; +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.IPFSNetwork.executeIPFSCommands; +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.net.SocketException; + import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONException; import org.json.JSONObject; -import java.io.*; -import java.net.Socket; -import java.net.SocketException; -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.*; -import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import io.ipfs.api.IPFS; public class PingCheck { private static final Logger PingSenderLogger = Logger.getLogger(PingCheck.class); public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); public static BufferedReader serverInput; - - public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { + public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -72,7 +82,6 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSON return APIResponse; } - if (pongResponse != null && (!pongResponse.equals("Pong"))) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); PingSenderLogger.info("Pong response not received"); @@ -82,7 +91,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSON APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong response not received"); - }else { + } else { PingSenderLogger.info("Ping Successful"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); output.close(); diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index a21bcc8e..466442dc 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -191,7 +191,6 @@ public static String networkInfo() throws IOException, JSONException { * Method to query the credits information * * @throws JSONException - * * @files QuorumSignedTransactions.json, MinedCreditsHistory.json */ public static JSONObject creditsInfo() throws JSONException { diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 5e00e999..55e32634 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -3,7 +3,6 @@ import static com.rubix.Resources.APIHandler.addPublicData; import static com.rubix.Resources.IPFSNetwork.IPFSNetworkLogger; import static com.rubix.Resources.IPFSNetwork.checkSwarmConnect; -import static com.rubix.Resources.IPFSNetwork.dhtOwnerCheck; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.forwardCheck; import static com.rubix.Resources.IPFSNetwork.listen; @@ -75,6 +74,23 @@ public class Functions { public static Logger FunctionsLogger = Logger.getLogger(Functions.class); + public static void setDir() { + String OSName = getOsName(); + if (OSName.contains("Windows")) + dirPath = "C:\\Rubix\\"; + else if (OSName.contains("Mac")) + dirPath = "/Applications/Rubix/"; + else if (OSName.contains("Linux")) + dirPath = "/home/" + getSystemUser() + "/Rubix/"; + else + System.exit(0); + } + + public static void setConfig() { + setDir(); + configPath = dirPath.concat("config.json"); + } + public static String buildVersion() throws IOException { String jarPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); jarPath = jarPath.split("\\.jar")[0]; @@ -113,23 +129,6 @@ public static String calculateFileHash(String filePath, String algorithm) { return hash; } - public static void setDir() { - String OSName = getOsName(); - if (OSName.contains("Windows")) - dirPath = "C:\\Rubix\\"; - else if (OSName.contains("Mac")) - dirPath = "/Applications/Rubix/"; - else if (OSName.contains("Linux")) - dirPath = "/home/" + getSystemUser() + "/Rubix/"; - else - System.exit(0); - } - - public static void setConfig() { - setDir(); - configPath = dirPath.concat("config.json"); - } - /** * This method sets the required paths used in the functions */ @@ -443,67 +442,6 @@ public static void listenThread(JSONObject connectObject) { } - /** - * This function check if the token is pinned by the given DID - * - * @param tokenID - * @param DID of owner of the token to be checked - * @return boolean value - */ - public static boolean checkTokenOwnershiByDID(String tokenID, String DID) { - boolean ownStatus = false; - String peerID = getValues(DATA_PATH + "DataTable.json", "peerid", - "didHash", DID); - try { - ArrayList owners = dhtOwnerCheck(tokenID); - if (owners.contains(peerID)) { - ownStatus = true; - } - - } catch (InterruptedException | JSONException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return ownStatus; - } - - public static int levelHeight() { - int creditsRequired = 0; - JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getlevel"; - URL URLobj_credit; - try { - URLobj_credit = new URL(GET_URL_credit); - HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); - con_credit.setRequestMethod("GET"); - int responseCode_credit = con_credit.getResponseCode(); - System.out.println("GET Response Code :: " + responseCode_credit); - if (responseCode_credit == HttpURLConnection.HTTP_OK) { - BufferedReader in_credit = new BufferedReader( - new InputStreamReader(con_credit.getInputStream())); - String inputLine_credit; - StringBuffer response_credit = new StringBuffer(); - while ((inputLine_credit = in_credit.readLine()) != null) { - response_credit.append(inputLine_credit); - } - in_credit.close(); - FunctionsLogger.debug("response from service " + response_credit.toString()); - resJsonData_credit = new JSONObject(response_credit.toString()); - int level_credit = resJsonData_credit.getInt("level"); - creditsRequired = (int) Math.pow(2, (2 + level_credit)); - FunctionsLogger.debug("credits required " + creditsRequired); - - return creditsRequired; - - } else - FunctionsLogger.debug("GET request not OK"); - - } catch (Exception e) { - FunctionsLogger.debug("GET request not worked " + e.getMessage()); - } - return creditsRequired; - } - /** * This function converts any integer to its binary form * @@ -949,10 +887,11 @@ public static String checkDirectory() throws JSONException { File didImage = new File(DATA_PATH + myDID + "/DID.png"); File widImage = new File(DATA_PATH + myDID + "/PublicShare.png"); - // File pvtImage = new File(DATA_PATH + myDID + "/PrivateShare.png"); - if (!didImage.exists() || !widImage.exists()) { + File pvtImage = new File(DATA_PATH + myDID + "/PrivateShare.png"); + if (!didImage.exists() || !widImage.exists() || !pvtImage.exists()) { + didImage.delete(); + didImage.delete(); didImage.delete(); - widImage.delete(); JSONObject result = new JSONObject(); result.put("message", "User not registered, create your Decentralised Identity!"); result.put("info", "Shares Images Missing"); @@ -1175,15 +1114,6 @@ public static void mineUpdate(String didHash, int credits) throws IOException, J } - public static String initHash() throws IOException { - String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - initPath = initPath.split("\\.jar")[0]; - initPath = initPath.split("file:", 2)[1]; - initPath = initPath + ".jar"; - String hash = calculateFileHash(initPath, "SHA3-256"); - return hash; - } - public static int checkHeartBeat(String peerId, String appName) { if (forwardCheck(appName, QUORUM_PORT, peerId)) { @@ -1467,6 +1397,15 @@ public static Double getBalance() throws JSONException { return balance; } + public static String initHash() throws IOException { + String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); + initPath = initPath.split("\\.jar")[0]; + initPath = initPath.split("file:", 2)[1]; + initPath = initPath + ".jar"; + String hash = calculateFileHash(initPath, "SHA3-256"); + return hash; + } + public static Double partTokenBalance(String tokenHash) throws JSONException { pathSet(); diff --git a/src/com/rubix/Resources/IPFSNetwork.java b/src/com/rubix/Resources/IPFSNetwork.java index 5cc6917c..9892b039 100644 --- a/src/com/rubix/Resources/IPFSNetwork.java +++ b/src/com/rubix/Resources/IPFSNetwork.java @@ -1,6 +1,5 @@ package com.rubix.Resources; -import static com.rubix.Constants.ConsensusConstants.MINE_XORER; import static com.rubix.Constants.IPFSConstants.bootstrap; import static com.rubix.Constants.IPFSConstants.daemon; import static com.rubix.Constants.IPFSConstants.forward; @@ -270,17 +269,6 @@ public static String addHashOnly(String fileName, IPFS ipfs) { return null; } - public static String getMineID(String stakedToken, IPFS ipfs) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < stakedToken.length(); i++) { - sb.append((char) (stakedToken.charAt(i) ^ MINE_XORER.charAt(i))); - } - // convert sb to IPFS multihash - String multihash = add(sb.toString(), ipfs); - - return multihash; - } - /** * This method pin objects to local storage See * ipfs pin From af553198af46bb3435d082dceef286301c9022fa Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sat, 19 Mar 2022 15:28:41 +0530 Subject: [PATCH 022/179] kappa 6 test Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 79 ++++++++------------ 1 file changed, 30 insertions(+), 49 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 6559342a..95556e84 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,13 +1,6 @@ package com.rubix.Consensus; import static com.rubix.Constants.ConsensusConstants.INIT_HASH; -import static com.rubix.Constants.MiningConstants.MINED_RBT; -import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; -import static com.rubix.Constants.MiningConstants.MINE_ID; -import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; -import static com.rubix.Constants.MiningConstants.MINE_TID; -import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; -import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; @@ -173,48 +166,36 @@ public void run() { executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - // ! mine details to sign - JSONObject mineDetToSign = new JSONObject(); - - try { - String mineData = in.readLine(); - // convert mineData to JSONObject - mineDetToSign = new JSONObject(mineData); - } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - Stake ID details (to be signed)"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - - if (mineDetToSign.length() == 3 && mineDetToSign.has( - MINE_ID) && mineDetToSign.has( - MINED_RBT) - && mineDetToSign.has(MINE_TID)) { - JSONObject stakingSigns = new JSONObject(); - - QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); - - stakingSigns.put( - STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - tokenHash)); - stakingSigns.put( - MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineDetToSign.getString(MINE_TID))); - stakingSigns.put( - MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineDetToSign.getString(MINED_RBT))); - stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineDetToSign.getString(MINE_ID))); - - out.println(stakingSigns.toString()); - } else { - QuorumConsensusLogger.debug("Incorrect stake details"); - out.println("445"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } + // if (mineDetToSign.length() == 3 && mineDetToSign.has( + // MINE_ID) && mineDetToSign.has( + // MINED_RBT) + // && mineDetToSign.has(MINE_TID)) { + // JSONObject stakingSigns = new JSONObject(); + + // QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); + + // stakingSigns.put( + // STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + + // "/PrivateShare.png", + // tokenHash)); + // stakingSigns.put( + // MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + // mineDetToSign.getString(MINE_TID))); + // stakingSigns.put( + // MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + // mineDetToSign.getString(MINED_RBT))); + // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + + // "/PrivateShare.png", + // mineDetToSign.getString(MINE_ID))); + + // out.println(stakingSigns.toString()); + // } else { + // QuorumConsensusLogger.debug("Incorrect stake details"); + // out.println("445"); + // socket.close(); + // serverSocket.close(); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + // } // ! receive credits equal to credits required to mine token From 8c9ecafaa26cd02b1322be7a992d695217fd4c68 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sat, 19 Mar 2022 22:58:14 +0530 Subject: [PATCH 023/179] valdiating stake tokens 2/ Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 192 ++++++++++--------- src/com/rubix/Consensus/StakeConsensus.java | 41 +++- 2 files changed, 136 insertions(+), 97 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 95556e84..5486f912 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -143,119 +143,121 @@ public void run() { String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); JSONArray bankArray = new JSONArray(bankFile); - // pick last object from bank array - JSONObject bankObject = bankArray.getJSONObject(0); - String tokenHash = bankObject.getString("tokenHash"); - tokenToStake.put(tokenHash); + if (bankArray.length() != 0) { - File tokenFile = new File(TOKENS_PATH + tokenHash); - File tokenchainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); + // pick last object from bank array + JSONObject bankObject = bankArray.getJSONObject(0); + String tokenHash = bankObject.getString("tokenHash"); + tokenToStake.put(tokenHash); - if (tokenFile.exists() && tokenchainFile.exists()) { + File tokenFile = new File(TOKENS_PATH + tokenHash); + File tokenchainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); tokenToStake.put(tokenChain); // ! token which will be staked out.println(tokenToStake); - } else { - QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); - out.println("445"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - // if (mineDetToSign.length() == 3 && mineDetToSign.has( - // MINE_ID) && mineDetToSign.has( - // MINED_RBT) - // && mineDetToSign.has(MINE_TID)) { - // JSONObject stakingSigns = new JSONObject(); - - // QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); - - // stakingSigns.put( - // STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + - // "/PrivateShare.png", - // tokenHash)); - // stakingSigns.put( - // MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - // mineDetToSign.getString(MINE_TID))); - // stakingSigns.put( - // MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - // mineDetToSign.getString(MINED_RBT))); - // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + - // "/PrivateShare.png", - // mineDetToSign.getString(MINE_ID))); - - // out.println(stakingSigns.toString()); - // } else { - // QuorumConsensusLogger.debug("Incorrect stake details"); - // out.println("445"); - // socket.close(); - // serverSocket.close(); - // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - // } - - // ! receive credits equal to credits required to mine token - - String credits = null; - try { - credits = in.readLine(); - // convert mineData to JSONObject - System.out.println("credits received " + credits); - } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - Adding Credits Failed"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } + // if (mineDetToSign.length() == 3 && mineDetToSign.has( + // MINE_ID) && mineDetToSign.has( + // MINED_RBT) + // && mineDetToSign.has(MINE_TID)) { + // JSONObject stakingSigns = new JSONObject(); + + // QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); + + // stakingSigns.put( + // STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + + // "/PrivateShare.png", + // tokenHash)); + // stakingSigns.put( + // MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + // mineDetToSign.getString(MINE_TID))); + // stakingSigns.put( + // MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + // mineDetToSign.getString(MINED_RBT))); + // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + + // "/PrivateShare.png", + // mineDetToSign.getString(MINE_ID))); + + // out.println(stakingSigns.toString()); + // } else { + // QuorumConsensusLogger.debug("Incorrect stake details"); + // out.println("445"); + // socket.close(); + // serverSocket.close(); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + // } + + // ! receive credits equal to credits required to mine token + + String credits = null; + try { + credits = in.readLine(); + // convert mineData to JSONObject + System.out.println("credits received " + credits); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - Adding Credits Failed"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } - JSONArray creditArray = new JSONArray(credits); + JSONArray creditArray = new JSONArray(credits); + + // Get level of token from advisory node + int creditsRequired = 0; + JSONObject resJsonData_credit = new JSONObject(); + String GET_URL_credit = SYNC_IP + "/getlevel"; + URL URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + QuorumConsensusLogger.debug("response from service " + response_credit.toString()); + resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + creditsRequired = (int) Math.pow(2, (2 + level_credit)); + QuorumConsensusLogger.debug("credits required " + creditsRequired); - // Get level of token from advisory node - int creditsRequired = 0; - JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getlevel"; - URL URLobj_credit = new URL(GET_URL_credit); - HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); - con_credit.setRequestMethod("GET"); - int responseCode_credit = con_credit.getResponseCode(); - System.out.println("GET Response Code :: " + responseCode_credit); - if (responseCode_credit == HttpURLConnection.HTTP_OK) { - BufferedReader in_credit = new BufferedReader( - new InputStreamReader(con_credit.getInputStream())); - String inputLine_credit; - StringBuffer response_credit = new StringBuffer(); - while ((inputLine_credit = in_credit.readLine()) != null) { - response_credit.append(inputLine_credit); - } - in_credit.close(); - QuorumConsensusLogger.debug("response from service " + response_credit.toString()); - resJsonData_credit = new JSONObject(response_credit.toString()); - int level_credit = resJsonData_credit.getInt("level"); - creditsRequired = (int) Math.pow(2, (2 + level_credit)); - QuorumConsensusLogger.debug("credits required " + creditsRequired); + } else + QuorumConsensusLogger.debug("GET request not worked"); - } else - QuorumConsensusLogger.debug("GET request not worked"); + if (!(creditArray.length() != creditsRequired) && !(creditsRequired != 0)) { + + QuorumConsensusLogger.debug("Credits received"); + out.println("200"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - if ((creditArray.length() != creditsRequired) && (creditsRequired != 0)) { + // ! store the credits + + } else { + + QuorumConsensusLogger.debug("Credits not received"); + out.println("446"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } - QuorumConsensusLogger.debug("Credits not received"); - out.println("446"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } else { - QuorumConsensusLogger.debug("Credits received"); - out.println("200"); + QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); + out.println("445"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - - // ! store the credits - } } else { diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index e0ce4dc6..1ad73097 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -66,7 +66,6 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject forward(appName, PORT + j, quorumID[j]); StakeConsensusLogger.debug( "Connected to " + quorumID[j] + "on port " + (PORT + j) + "with AppName" + appName); - qSocket[j] = new Socket("127.0.0.1", PORT + j); qSocket[j].setSoTimeout(socketTimeOut); qIn[j] = new BufferedReader(new InputStreamReader(qSocket[j].getInputStream())); @@ -74,14 +73,52 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject qOut[j].println(operation); if (operation.equals("alpha-stake-token")) { + String response = null; qOut[j].println(data.toString()); StakeConsensusLogger.debug("Token Details sent for validation..."); try { - qIn[j].readLine(); + response = qIn[j].readLine(); StakeConsensusLogger.debug("Token Details validated. Received stake token details.."); } catch (SocketException e) { + StakeConsensusLogger.debug("Token Details validation failed. Received null response"); + } + if (!response.contains("44")) { + + Boolean verified = false; + JSONArray stakeTokenArray = new JSONArray(response); + String stakeTokenHash = stakeTokenArray.getString(0); + String stakeTCObject = stakeTokenArray.getString(1); + JSONArray stakeTC = new JSONArray(stakeTCObject); + + // ! check ownership of stakeTC + + if (verified) { + qOut[j].println("alpha-stake-token-verified"); + StakeConsensusLogger.debug("Waiting for stake signatures"); + + try { + response = qIn[j].readLine(); + StakeConsensusLogger + .debug("Received stake token signatures. Sending Credits"); + } catch (SocketException e) { + StakeConsensusLogger + .debug("Token Details validation failed. Received null response"); + } + + // ! valodate signatures + + // ! send credits + + if (!response.contains("44")) { + qResponse[j] = response; + } + } + + } else if (response.equals("444")) { + StakeConsensusLogger.debug("Token Details validation failed. Received null response"); + } else if (response.equals("445")) { } From c59527d6c2da43378f6508e8df50d6e12e93d50a Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sun, 20 Mar 2022 01:04:09 +0530 Subject: [PATCH 024/179] added logs on staking 4/ Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/InitiatorConsensus.java | 2 ++ src/com/rubix/Consensus/StakeConsensus.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index c14667d6..c540fd1b 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -289,6 +289,8 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri InitiatorConsensusLogger .debug("waiting for " + quorumSize + " +signs " + role); if (role.equals("alpha")) { + InitiatorConsensusLogger + .debug("Picking Quorum for Staking " + quorumID[j]); signedAphaQuorumArray.put(quorumID[j]); } while (quorumResponse[index] < minQuorum(quorumSize)) { diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 1ad73097..8463b483 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -44,6 +44,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject BufferedReader[] qIn = new BufferedReader[signedAphaQuorumArray.length()]; String[] quorumID = new String[signedAphaQuorumArray.length()]; + StakeConsensusLogger.debug("Initiating Staking for " + signedAphaQuorumArray.length() + "Alpha Quorums..."); + try { for (int j = 0; j < signedAphaQuorumArray.length(); j++) From 1770b86f4fad2b07761d5ed2e65164c7f0c08757 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sun, 20 Mar 2022 02:18:45 +0530 Subject: [PATCH 025/179] arrange stake res Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 9 +++++++-- src/com/rubix/Mining/ProofCredits.java | 6 +++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 8463b483..5bd67a13 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -34,7 +34,7 @@ public class StakeConsensus { // sign on mining token // same object will be added to tokenchains of staked and mined token - public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject data, IPFS ipfs, int PORT, + public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject data, IPFS ipfs, int PORT, String operation) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -44,7 +44,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject BufferedReader[] qIn = new BufferedReader[signedAphaQuorumArray.length()]; String[] quorumID = new String[signedAphaQuorumArray.length()]; - StakeConsensusLogger.debug("Initiating Staking for " + signedAphaQuorumArray.length() + "Alpha Quorums..."); + StakeConsensusLogger.debug("Initiating Staking for " + signedAphaQuorumArray.length() + " Alpha Quorums..."); try { @@ -94,6 +94,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject String stakeTCObject = stakeTokenArray.getString(1); JSONArray stakeTC = new JSONArray(stakeTCObject); + stakeDetails.put("stakeToken", stakeTokenHash); + // ! check ownership of stakeTC if (verified) { @@ -133,9 +135,12 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } ; + return stakeDetails; + } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); } + return stakeDetails; } } diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 705f5bfc..90ae80eb 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -354,6 +354,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } } JSONObject stakingData = new JSONObject(); + String tkHash = null; for (int i = 0; i < token.length(); i++) { writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); @@ -408,6 +409,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject.put("nextHash", calculateHash(tid, "SHA3-256")); tokenChainGenesisObject.put("previousHash", ""); stakingData = tokenChainGenesisObject; + tkHash = tokenHash; tokenChainArray.put(tokenChainGenesisObject); writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); @@ -419,10 +421,12 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } // ! new token will now need a staked token - StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, + JSONObject stakeDetails = StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, stakingData, ipfs, SEND_PORT + 3, "alpha-stake-token"); + updateJSON("add", TOKENCHAIN_PATH + tkHash + ".json", stakeDetails.toString()); + if (!(InitiatorConsensus.quorumSignature.length() >= 3 * minQuorum(7))) { APIResponse.put("did", DID); APIResponse.put("tid", "null"); From 16bc3b1ea42d265fae5cbedac04bb45d3e0dd228 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sun, 20 Mar 2022 10:26:23 +0530 Subject: [PATCH 026/179] response fix staking consensus Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 157 ++++++++++--------- src/com/rubix/Consensus/StakeConsensus.java | 20 +-- 2 files changed, 93 insertions(+), 84 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 5486f912..19df4759 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -159,93 +159,102 @@ public void run() { // ! token which will be staked out.println(tokenToStake); - // if (mineDetToSign.length() == 3 && mineDetToSign.has( - // MINE_ID) && mineDetToSign.has( - // MINED_RBT) - // && mineDetToSign.has(MINE_TID)) { - // JSONObject stakingSigns = new JSONObject(); - - // QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); - - // stakingSigns.put( - // STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + - // "/PrivateShare.png", - // tokenHash)); - // stakingSigns.put( - // MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - // mineDetToSign.getString(MINE_TID))); - // stakingSigns.put( - // MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - // mineDetToSign.getString(MINED_RBT))); - // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + - // "/PrivateShare.png", - // mineDetToSign.getString(MINE_ID))); - - // out.println(stakingSigns.toString()); - // } else { - // QuorumConsensusLogger.debug("Incorrect stake details"); - // out.println("445"); - // socket.close(); - // serverSocket.close(); - // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - // } - - // ! receive credits equal to credits required to mine token - - String credits = null; try { - credits = in.readLine(); - // convert mineData to JSONObject - System.out.println("credits received " + credits); + response = in.readLine(); } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - Adding Credits Failed"); + QuorumConsensusLogger + .debug("Sender Input Stream Null - Stake Token Validation by Miner Failed"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - JSONArray creditArray = new JSONArray(credits); - - // Get level of token from advisory node - int creditsRequired = 0; - JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getlevel"; - URL URLobj_credit = new URL(GET_URL_credit); - HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); - con_credit.setRequestMethod("GET"); - int responseCode_credit = con_credit.getResponseCode(); - System.out.println("GET Response Code :: " + responseCode_credit); - if (responseCode_credit == HttpURLConnection.HTTP_OK) { - BufferedReader in_credit = new BufferedReader( - new InputStreamReader(con_credit.getInputStream())); - String inputLine_credit; - StringBuffer response_credit = new StringBuffer(); - while ((inputLine_credit = in_credit.readLine()) != null) { - response_credit.append(inputLine_credit); + if (response == "alpha-stake-token-verified") { + + JSONObject stakingSigns = new JSONObject(); + + // QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); + + // stakingSigns.put( + // STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + + // "/PrivateShare.png", + // tokenHash)); + // stakingSigns.put( + // MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + // mineDetToSign.getString(MINE_TID))); + // stakingSigns.put( + // MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + // mineDetToSign.getString(MINED_RBT))); + // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + + // "/PrivateShare.png", + // mineDetToSign.getString(MINE_ID))); + + out.println(stakingSigns.toString()); + + // ! receive credits equal to credits required to mine token + + String credits = null; + try { + credits = in.readLine(); + // convert mineData to JSONObject + System.out.println("credits received " + credits); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - Adding Credits Failed"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - in_credit.close(); - QuorumConsensusLogger.debug("response from service " + response_credit.toString()); - resJsonData_credit = new JSONObject(response_credit.toString()); - int level_credit = resJsonData_credit.getInt("level"); - creditsRequired = (int) Math.pow(2, (2 + level_credit)); - QuorumConsensusLogger.debug("credits required " + creditsRequired); - } else - QuorumConsensusLogger.debug("GET request not worked"); + JSONArray creditArray = new JSONArray(credits); + + // Get level of token from advisory node + int creditsRequired = 0; + JSONObject resJsonData_credit = new JSONObject(); + String GET_URL_credit = SYNC_IP + "/getlevel"; + URL URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + QuorumConsensusLogger.debug("response from service " + response_credit.toString()); + resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + creditsRequired = (int) Math.pow(2, (2 + level_credit)); + QuorumConsensusLogger.debug("credits required " + creditsRequired); + + } else + QuorumConsensusLogger.debug("GET request not worked"); + + if (!(creditArray.length() != creditsRequired) && !(creditsRequired != 0)) { + + QuorumConsensusLogger.debug("Credits received"); + out.println("200"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - if (!(creditArray.length() != creditsRequired) && !(creditsRequired != 0)) { + // ! store the credits - QuorumConsensusLogger.debug("Credits received"); - out.println("200"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } else { - // ! store the credits + QuorumConsensusLogger.debug("Credits not received"); + out.println("447"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } } else { - - QuorumConsensusLogger.debug("Credits not received"); + QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); out.println("446"); socket.close(); serverSocket.close(); @@ -253,7 +262,7 @@ public void run() { } } else { - QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); + QuorumConsensusLogger.debug("Incorrect stake details"); out.println("445"); socket.close(); serverSocket.close(); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 5bd67a13..b0edcf31 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -44,7 +44,8 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON BufferedReader[] qIn = new BufferedReader[signedAphaQuorumArray.length()]; String[] quorumID = new String[signedAphaQuorumArray.length()]; - StakeConsensusLogger.debug("Initiating Staking for " + signedAphaQuorumArray.length() + " Alpha Quorums..."); + StakeConsensusLogger.debug("Initiating Staking with " + signedAphaQuorumArray.length() + " Alpha Quorums: " + + signedAphaQuorumArray); try { @@ -75,21 +76,20 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON qOut[j].println(operation); if (operation.equals("alpha-stake-token")) { - String response = null; qOut[j].println(data.toString()); StakeConsensusLogger.debug("Token Details sent for validation..."); try { - response = qIn[j].readLine(); + qResponse[j] = qIn[j].readLine(); StakeConsensusLogger.debug("Token Details validated. Received stake token details.."); } catch (SocketException e) { StakeConsensusLogger.debug("Token Details validation failed. Received null response"); } - if (!response.contains("44")) { + if (!qResponse[j].contains("44")) { Boolean verified = false; - JSONArray stakeTokenArray = new JSONArray(response); + JSONArray stakeTokenArray = new JSONArray(qResponse[j]); String stakeTokenHash = stakeTokenArray.getString(0); String stakeTCObject = stakeTokenArray.getString(1); JSONArray stakeTC = new JSONArray(stakeTCObject); @@ -103,7 +103,7 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON StakeConsensusLogger.debug("Waiting for stake signatures"); try { - response = qIn[j].readLine(); + qResponse[j] = qIn[j].readLine(); StakeConsensusLogger .debug("Received stake token signatures. Sending Credits"); } catch (SocketException e) { @@ -115,14 +115,14 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON // ! send credits - if (!response.contains("44")) { - qResponse[j] = response; + if (!qResponse[j].contains("44")) { + // qResponse[j] = response; } } - } else if (response.equals("444")) { + } else if (qResponse[j].equals("444")) { StakeConsensusLogger.debug("Token Details validation failed. Received null response"); - } else if (response.equals("445")) { + } else if (qResponse[j].equals("445")) { } From f25655cc64de9a48b4f3ada6c90c9935f5e3f055 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sun, 20 Mar 2022 12:33:09 +0530 Subject: [PATCH 027/179] quorum connection check Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 ++ src/com/rubix/Mining/ProofCredits.java | 4 +++- src/com/rubix/Resources/Functions.java | 3 +-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index b0edcf31..094b734f 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -57,6 +57,8 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON int j = i; quorumThreads[i] = new Thread(() -> { try { + StakeConsensusLogger.debug("Connecting to Quorum: " + quorumID[j]); + swarmConnectP2P(quorumID[j], ipfs); syncDataTable(null, quorumID[j]); String quorumDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 90ae80eb..ff101734 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -424,8 +424,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONObject stakeDetails = StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, stakingData, ipfs, SEND_PORT + 3, "alpha-stake-token"); + JSONArray tempArray = new JSONArray(); + tempArray.put(stakeDetails); - updateJSON("add", TOKENCHAIN_PATH + tkHash + ".json", stakeDetails.toString()); + updateJSON("add", TOKENCHAIN_PATH + tkHash + ".json", tempArray.toString()); if (!(InitiatorConsensus.quorumSignature.length() >= 3 * minQuorum(7))) { APIResponse.put("did", DID); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 55e32634..7a702ac6 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -111,7 +111,6 @@ public static String calculateFileHash(String filePath, String algorithm) { // check if file exists at the filePath File file = new File(filePath); if (file.exists()) { - System.out.println("File Hashing..."); FileInputStream fis = new FileInputStream(file); byte[] byteArray = new byte[1024]; int bytesCount = 0; @@ -123,7 +122,7 @@ public static String calculateFileHash(String filePath, String algorithm) { fis.close(); } } catch (NoSuchAlgorithmException | IOException e) { - FunctionsLogger.error("Invalid Cryptographic Algorithm", e); + FunctionsLogger.error("Invalid Cryptographic Algorithm while calculating file hash", e); e.printStackTrace(); } return hash; From 06afcc126b4d2398b679ccf1c29f3dfe240d760f Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sun, 20 Mar 2022 12:57:10 +0530 Subject: [PATCH 028/179] fix thread issue Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 094b734f..00927bf1 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -134,6 +134,7 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON StakeConsensusLogger.error("Error in quorum consensus thread: " + e); } }); + quorumThreads[j].start(); } ; From e0ca337a054315de67844bb8f2e2474e25da1948 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sun, 20 Mar 2022 21:38:09 +0530 Subject: [PATCH 029/179] staking logic complete comm. Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 244 ++++++++++++------ src/com/rubix/Consensus/StakeConsensus.java | 59 ++++- src/com/rubix/Mining/ProofCredits.java | 1 + .../rubix/TokenTransfer/TokenReceiver.java | 4 +- 4 files changed, 217 insertions(+), 91 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 19df4759..effc7e85 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,6 +1,10 @@ package com.rubix.Consensus; import static com.rubix.Constants.ConsensusConstants.INIT_HASH; +import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; +import static com.rubix.Constants.MiningConstants.MINE_ID; +import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; +import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; @@ -17,13 +21,16 @@ import static com.rubix.Resources.Functions.initHash; import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.Functions.readFile; +import static com.rubix.Resources.Functions.strToIntArray; import static com.rubix.Resources.Functions.syncDataTable; import static com.rubix.Resources.Functions.updateJSON; import static com.rubix.Resources.Functions.writeToFile; import static com.rubix.Resources.IPFSNetwork.add; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; +import static com.rubix.Resources.IPFSNetwork.pin; +import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; @@ -38,7 +45,10 @@ import java.text.ParseException; import java.util.HashSet; +import javax.imageio.ImageIO; + import com.rubix.AuthenticateNode.Authenticate; +import com.rubix.AuthenticateNode.PropImage; import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; @@ -130,10 +140,12 @@ public void run() { QuorumConsensusLogger.debug("Validating new token details..."); - boolean isValid = false; + boolean isValid = true; // ! check token is in same level // ! validate mined token hash and ownership + JSONObject genesisBlock = new JSONObject(response); + System.out.println(genesisBlock); if (isValid) { @@ -153,106 +165,180 @@ public void run() { File tokenFile = new File(TOKENS_PATH + tokenHash); File tokenchainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); - String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); - tokenToStake.put(tokenChain); - - // ! token which will be staked - out.println(tokenToStake); - - try { - response = in.readLine(); - } catch (SocketException e) { - QuorumConsensusLogger - .debug("Sender Input Stream Null - Stake Token Validation by Miner Failed"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - - if (response == "alpha-stake-token-verified") { - - JSONObject stakingSigns = new JSONObject(); - - // QuorumConsensusLogger.debug("Mine ID: " + mineDetToSign.getString(MINE_ID)); - - // stakingSigns.put( - // STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + - // "/PrivateShare.png", - // tokenHash)); - // stakingSigns.put( - // MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - // mineDetToSign.getString(MINE_TID))); - // stakingSigns.put( - // MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - // mineDetToSign.getString(MINED_RBT))); - // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + - // "/PrivateShare.png", - // mineDetToSign.getString(MINE_ID))); - - out.println(stakingSigns.toString()); - - // ! receive credits equal to credits required to mine token + // check if token file and tokenchain file exists + if (tokenFile.exists() && tokenchainFile.exists()) { + + String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); + tokenToStake.put(tokenChain); + + String hashString = tokenHash.concat(senderDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + BufferedImage privateShare = ImageIO + .read(new File( + DATA_PATH.concat(senderDidIpfsHash).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(privateShare); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + tokenToStake.put(positions); + // ! token which will be staked + out.println(tokenToStake); - String credits = null; try { - credits = in.readLine(); - // convert mineData to JSONObject - System.out.println("credits received " + credits); + response = in.readLine(); } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - Adding Credits Failed"); + QuorumConsensusLogger + .debug("Sender Input Stream Null - Stake Token Validation by Miner Failed"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - JSONArray creditArray = new JSONArray(credits); - - // Get level of token from advisory node - int creditsRequired = 0; - JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getlevel"; - URL URLobj_credit = new URL(GET_URL_credit); - HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); - con_credit.setRequestMethod("GET"); - int responseCode_credit = con_credit.getResponseCode(); - System.out.println("GET Response Code :: " + responseCode_credit); - if (responseCode_credit == HttpURLConnection.HTTP_OK) { - BufferedReader in_credit = new BufferedReader( - new InputStreamReader(con_credit.getInputStream())); - String inputLine_credit; - StringBuffer response_credit = new StringBuffer(); - while ((inputLine_credit = in_credit.readLine()) != null) { - response_credit.append(inputLine_credit); + if (response == "alpha-stake-token-verified") { + + JSONObject stakingSigns = new JSONObject(); + + genesisBlock.put("stakingToken", tokenHash); + + stakingSigns.put( + STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + + "/PrivateShare.png", + tokenHash)); + stakingSigns.put( + MINING_TID_SIGN, + getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + genesisBlock.getString("tid"))); + stakingSigns.put( + MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + genesisBlock.getString("tokenHash"))); + + genesisBlock.put("stakerSignatures", stakingSigns); + + // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + + // "/PrivateShare.png", + // mineDetToSign.getString(MINE_ID))); + + FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mystake.txt"), + true); + shareWriter.write(genesisBlock.toString()); + shareWriter.close(); + File readStake = new File(LOGGER_PATH + "mystake.txt"); + String mineID = add(readStake.toString(), ipfs); + pin(mineID, ipfs); + + File stakeFile = new File( + WALLET_DATA_PATH.concat("/Stake/").concat(mineID).concat(".json")); + if (!stakeFile.exists()) + stakeFile.createNewFile(); + writeToFile(stakeFile.toString(), genesisBlock.toString(), false); + + // QuorumConsensusLogger.debug("Credit object: " + credit); + // QuorumConsensusLogger.debug("Credit Hash: " + calculateHash(credit, + // "SHA3-256")); + // JSONObject storeDetailsQuorum = new JSONObject(); + // storeDetailsQuorum.put("tid", transactionID); + // storeDetailsQuorum.put("consensusID", verifySenderHash); + // storeDetailsQuorum.put("sign", senderPrivatePos); + // storeDetailsQuorum.put("credits", credit); + // storeDetailsQuorum.put("creditHash", calculateHash(credit, "SHA3-256")); + // storeDetailsQuorum.put("senderdid", senderDidIpfsHash); + // storeDetailsQuorum.put("Date", Functions.getCurrentUtcTime()); + // 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 + "mystake.txt"); + + stakingSigns.put(MINE_ID, mineID); + + QuorumConsensusLogger.debug("Staking Token Staked Successfully. MINE ID: " + + mineID); + + out.println(stakingSigns.toString()); + + // ! receive credits equal to credits required to mine token + + String credits = null; + try { + credits = in.readLine(); + // convert mineData to JSONObject + System.out.println("credits received " + credits); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - Adding Credits Failed"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - in_credit.close(); - QuorumConsensusLogger.debug("response from service " + response_credit.toString()); - resJsonData_credit = new JSONObject(response_credit.toString()); - int level_credit = resJsonData_credit.getInt("level"); - creditsRequired = (int) Math.pow(2, (2 + level_credit)); - QuorumConsensusLogger.debug("credits required " + creditsRequired); - } else - QuorumConsensusLogger.debug("GET request not worked"); - - if (!(creditArray.length() != creditsRequired) && !(creditsRequired != 0)) { + System.out.println("credits received " + credits); - QuorumConsensusLogger.debug("Credits received"); + // JSONArray creditArray = new JSONArray(credits); + + // // Get level of token from advisory node + // int creditsRequired = 0; + // JSONObject resJsonData_credit = new JSONObject(); + // String GET_URL_credit = SYNC_IP + "/getlevel"; + // URL URLobj_credit = new URL(GET_URL_credit); + // HttpURLConnection con_credit = (HttpURLConnection) + // URLobj_credit.openConnection(); + // con_credit.setRequestMethod("GET"); + // int responseCode_credit = con_credit.getResponseCode(); + // System.out.println("GET Response Code :: " + responseCode_credit); + // if (responseCode_credit == HttpURLConnection.HTTP_OK) { + // BufferedReader in_credit = new BufferedReader( + // new InputStreamReader(con_credit.getInputStream())); + // String inputLine_credit; + // StringBuffer response_credit = new StringBuffer(); + // while ((inputLine_credit = in_credit.readLine()) != null) { + // response_credit.append(inputLine_credit); + // } + // in_credit.close(); + // QuorumConsensusLogger + // .debug("response from service " + response_credit.toString()); + // resJsonData_credit = new JSONObject(response_credit.toString()); + // int level_credit = resJsonData_credit.getInt("level"); + // creditsRequired = (int) Math.pow(2, (2 + level_credit)); + // QuorumConsensusLogger.debug("credits required " + creditsRequired); + + // } else + // QuorumConsensusLogger.debug("GET request not worked"); + + // if (!(creditArray.length() != creditsRequired) && !(creditsRequired != 0)) { + + // QuorumConsensusLogger.debug("Credits received"); + // out.println("200"); + // socket.close(); + // serverSocket.close(); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + + // // ! store the credits + + // } else { + + // QuorumConsensusLogger.debug("Credits not received"); + // out.println("448"); + // socket.close(); + // serverSocket.close(); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + // } + QuorumConsensusLogger.debug("Staking Completed!"); out.println("200"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - // ! store the credits - } else { - - QuorumConsensusLogger.debug("Credits not received"); + QuorumConsensusLogger.debug("Token file not found"); out.println("447"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - } else { QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); out.println("446"); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 00927bf1..27625656 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -2,6 +2,7 @@ import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.calculateHash; import static com.rubix.Resources.Functions.getValues; import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.Functions.syncDataTable; @@ -25,6 +26,7 @@ public class StakeConsensus { public static Logger StakeConsensusLogger = Logger.getLogger(StakeConsensus.class); private static int socketTimeOut = 120000; public static volatile JSONObject stakeDetails = new JSONObject(); + private static volatile boolean STAKE_SUCCESS = false; // mine ID // QST_Height // staker DID @@ -90,17 +92,43 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON } if (!qResponse[j].contains("44")) { - Boolean verified = false; + Boolean ownerCheck = false; JSONArray stakeTokenArray = new JSONArray(qResponse[j]); String stakeTokenHash = stakeTokenArray.getString(0); String stakeTCObject = stakeTokenArray.getString(1); + String positionsArray = stakeTokenArray.getString(2); JSONArray stakeTC = new JSONArray(stakeTCObject); - stakeDetails.put("stakeToken", stakeTokenHash); - - // ! check ownership of stakeTC + // ! check ownership of stakeTC from Token Receiver logic + + JSONObject lastObject = stakeTC.getJSONObject(stakeTCObject.length() - 1); + StakeConsensusLogger.debug("Last Object = " + lastObject); + if (lastObject.has("owner")) { + StakeConsensusLogger.debug("Checking ownership"); + String owner = lastObject.getString("owner"); + String tokens = stakeTokenHash; + String hashString = tokens.concat(quorumID[j]); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + String ownerIdentity = hashForPositions.concat(positionsArray); + String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + + StakeConsensusLogger.debug("Ownership Here Sender Calculation"); + StakeConsensusLogger.debug("tokens: " + tokens); + StakeConsensusLogger.debug("hashString: " + hashString); + StakeConsensusLogger.debug("hashForPositions: " + hashForPositions); + StakeConsensusLogger.debug("p1: " + positionsArray); + StakeConsensusLogger.debug("ownerIdentity: " + ownerIdentity); + StakeConsensusLogger.debug("ownerIdentityHash: " + ownerRecalculated); + + if (!owner.equals(ownerRecalculated)) { + ownerCheck = false; + StakeConsensusLogger.debug("Ownership Check Failed"); + } + } - if (verified) { + if (ownerCheck && !STAKE_SUCCESS) { + StakeConsensusLogger.debug("Ownership Check Success"); + STAKE_SUCCESS = true; qOut[j].println("alpha-stake-token-verified"); StakeConsensusLogger.debug("Waiting for stake signatures"); @@ -113,13 +141,26 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON .debug("Token Details validation failed. Received null response"); } - // ! valodate signatures + if (!qResponse[j].contains("44")) { - // ! send credits + // ! valodate signatures + StakeConsensusLogger.debug("Validating Signatures"); - if (!qResponse[j].contains("44")) { - // qResponse[j] = response; + // ! add mine signs to tokenchain + StakeConsensusLogger.debug("Adding mine signatures"); + JSONObject mineSigns = new JSONObject(qResponse[j]); + + stakeDetails = mineSigns; + + stakeDetails.put("stakedToken", stakeTokenHash); + + // ! send credits + StakeConsensusLogger.debug("Sending Credits"); + + qOut[j].println("staking-success"); } + } else { + StakeConsensusLogger.debug("Ownership Check Failed"); } } else if (qResponse[j].equals("444")) { diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index ff101734..e114d86c 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -406,6 +406,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject.put("owner", ownerIdentityHash); tokenChainGenesisObject.put("blockNumber", 0); tokenChainGenesisObject.put("QSTHeight", QSTHeight); + tokenChainGenesisObject.put("tokenHash", tokenHash); tokenChainGenesisObject.put("nextHash", calculateHash(tid, "SHA3-256")); tokenChainGenesisObject.put("previousHash", ""); stakingData = tokenChainGenesisObject; diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 6d7ef1af..feed78f0 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -128,8 +128,8 @@ public static String receive() { sk.close(); ss.close(); return APIResponse.toString(); - } + TokenReceiverLogger.debug("Data Received: " + senderPeerID); swarmConnectP2P(senderPeerID, ipfs); @@ -143,7 +143,6 @@ 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"); - output.close(); input.close(); sk.close(); @@ -161,7 +160,6 @@ public static String receive() { APIResponse.put("message", "Sender details not available"); TokenReceiverLogger.info("Sender details not available"); /* executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); */ - output.close(); input.close(); sk.close(); From 5d637bcf627a1b893533bab8a27cfadefcbd8a4e Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 21 Mar 2022 13:49:20 +0530 Subject: [PATCH 030/179] staking order fix Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 4 +- src/com/rubix/Consensus/StakeConsensus.java | 76 +++++++++++--------- src/com/rubix/Mining/ProofCredits.java | 23 +++--- 3 files changed, 54 insertions(+), 49 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index effc7e85..f72471a5 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -340,7 +340,6 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } } else { - QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); out.println("446"); socket.close(); serverSocket.close(); @@ -348,7 +347,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", } } else { - QuorumConsensusLogger.debug("Incorrect stake details"); + QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); out.println("445"); socket.close(); serverSocket.close(); @@ -356,6 +355,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", } } else { + QuorumConsensusLogger.debug("Incorrect stake details"); out.println("444"); socket.close(); serverSocket.close(); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 27625656..9e7cb471 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -44,7 +44,7 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON Socket[] qSocket = new Socket[signedAphaQuorumArray.length()]; PrintStream[] qOut = new PrintStream[signedAphaQuorumArray.length()]; BufferedReader[] qIn = new BufferedReader[signedAphaQuorumArray.length()]; - String[] quorumID = new String[signedAphaQuorumArray.length()]; + String[] quorumPID = new String[signedAphaQuorumArray.length()]; StakeConsensusLogger.debug("Initiating Staking with " + signedAphaQuorumArray.length() + " Alpha Quorums: " + signedAphaQuorumArray); @@ -52,27 +52,27 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON try { for (int j = 0; j < signedAphaQuorumArray.length(); j++) - quorumID[j] = signedAphaQuorumArray.getString(j); + quorumPID[j] = signedAphaQuorumArray.getString(j); Thread[] quorumThreads = new Thread[signedAphaQuorumArray.length()]; for (int i = 0; i < signedAphaQuorumArray.length(); i++) { int j = i; quorumThreads[i] = new Thread(() -> { try { - StakeConsensusLogger.debug("Connecting to Quorum: " + quorumID[j]); + StakeConsensusLogger.debug("Connecting to Quorum: " + quorumPID[j]); - swarmConnectP2P(quorumID[j], ipfs); - syncDataTable(null, quorumID[j]); + swarmConnectP2P(quorumPID[j], ipfs); + syncDataTable(null, quorumPID[j]); String quorumDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", - quorumID[j]); + quorumPID[j]); String quorumWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "peerid", - quorumID[j]); + quorumPID[j]); nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); - String appName = quorumID[j].concat("alpha"); - StakeConsensusLogger.debug("quourm ID " + quorumID[j] + " appname " + appName); - forward(appName, PORT + j, quorumID[j]); + String appName = quorumPID[j].concat("alpha"); + StakeConsensusLogger.debug("quourm ID " + quorumPID[j] + " appname " + appName); + forward(appName, PORT + j, quorumPID[j]); StakeConsensusLogger.debug( - "Connected to " + quorumID[j] + "on port " + (PORT + j) + "with AppName" + appName); + "Connected to " + quorumPID[j] + " on port " + (PORT + j) + "with AppName" + appName); qSocket[j] = new Socket("127.0.0.1", PORT + j); qSocket[j].setSoTimeout(socketTimeOut); qIn[j] = new BufferedReader(new InputStreamReader(qSocket[j].getInputStream())); @@ -86,13 +86,15 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON try { qResponse[j] = qIn[j].readLine(); - StakeConsensusLogger.debug("Token Details validated. Received stake token details.."); } catch (SocketException e) { StakeConsensusLogger.debug("Token Details validation failed. Received null response"); } if (!qResponse[j].contains("44")) { + StakeConsensusLogger.debug("Token Details validated. Received stake token details.."); Boolean ownerCheck = false; + String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", + quorumPID[j]); JSONArray stakeTokenArray = new JSONArray(qResponse[j]); String stakeTokenHash = stakeTokenArray.getString(0); String stakeTCObject = stakeTokenArray.getString(1); @@ -101,29 +103,33 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON // ! check ownership of stakeTC from Token Receiver logic - JSONObject lastObject = stakeTC.getJSONObject(stakeTCObject.length() - 1); - StakeConsensusLogger.debug("Last Object = " + lastObject); - if (lastObject.has("owner")) { - StakeConsensusLogger.debug("Checking ownership"); - String owner = lastObject.getString("owner"); - String tokens = stakeTokenHash; - String hashString = tokens.concat(quorumID[j]); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - String ownerIdentity = hashForPositions.concat(positionsArray); - String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); - - StakeConsensusLogger.debug("Ownership Here Sender Calculation"); - StakeConsensusLogger.debug("tokens: " + tokens); - StakeConsensusLogger.debug("hashString: " + hashString); - StakeConsensusLogger.debug("hashForPositions: " + hashForPositions); - StakeConsensusLogger.debug("p1: " + positionsArray); - StakeConsensusLogger.debug("ownerIdentity: " + ownerIdentity); - StakeConsensusLogger.debug("ownerIdentityHash: " + ownerRecalculated); - - if (!owner.equals(ownerRecalculated)) { - ownerCheck = false; - StakeConsensusLogger.debug("Ownership Check Failed"); + if (stakeTC.length() != 0 && stakeTokenHash != null && positionsArray != null) { + JSONObject lastObject = stakeTC.getJSONObject(stakeTCObject.length() - 1); + StakeConsensusLogger.debug("Last Object = " + lastObject); + if (lastObject.has("owner")) { + StakeConsensusLogger.debug("Checking ownership"); + String owner = lastObject.getString("owner"); + String tokens = stakeTokenHash; + String hashString = tokens.concat(stakerDID); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + String ownerIdentity = hashForPositions.concat(positionsArray); + String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + + StakeConsensusLogger.debug("Ownership Here Sender Calculation"); + StakeConsensusLogger.debug("tokens: " + tokens); + StakeConsensusLogger.debug("hashString: " + hashString); + StakeConsensusLogger.debug("hashForPositions: " + hashForPositions); + StakeConsensusLogger.debug("p1: " + positionsArray); + StakeConsensusLogger.debug("ownerIdentity: " + ownerIdentity); + StakeConsensusLogger.debug("ownerIdentityHash: " + ownerRecalculated); + + if (!owner.equals(ownerRecalculated)) { + ownerCheck = false; + StakeConsensusLogger.debug("Ownership Check Failed"); + } } + } else { + StakeConsensusLogger.debug("insufficient stake token height details"); } if (ownerCheck && !STAKE_SUCCESS) { @@ -164,7 +170,7 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON } } else if (qResponse[j].equals("444")) { - StakeConsensusLogger.debug("Token Details validation failed. Received null response"); + StakeConsensusLogger.debug("Error response from staker (insuff). Skipping..."); } else if (qResponse[j].equals("445")) { } diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index e114d86c..461f7484 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -353,8 +353,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } } } - JSONObject stakingData = new JSONObject(); - String tkHash = null; + // JSONObject stakingData = new JSONObject(); + // String tkHash = null; for (int i = 0; i < token.length(); i++) { writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); @@ -409,10 +409,16 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject.put("tokenHash", tokenHash); tokenChainGenesisObject.put("nextHash", calculateHash(tid, "SHA3-256")); tokenChainGenesisObject.put("previousHash", ""); - stakingData = tokenChainGenesisObject; - tkHash = tokenHash; + // stakingData = tokenChainGenesisObject; + // tkHash = tokenHash; tokenChainArray.put(tokenChainGenesisObject); + // ! new token will now need a staked token + JSONObject stakeDetails = StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, + tokenChainGenesisObject, ipfs, SEND_PORT + 3, + "alpha-stake-token"); + tokenChainArray.put(stakeDetails); + writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); @@ -421,14 +427,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON updateJSON("add", PAYMENTS_PATH + "BNK00.json", tempArray.toString()); } - // ! new token will now need a staked token - JSONObject stakeDetails = StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, - stakingData, ipfs, SEND_PORT + 3, - "alpha-stake-token"); - JSONArray tempArray = new JSONArray(); - tempArray.put(stakeDetails); - - updateJSON("add", TOKENCHAIN_PATH + tkHash + ".json", tempArray.toString()); + // updateJSON("add", TOKENCHAIN_PATH + tkHash + ".json", tempArray.toString()); if (!(InitiatorConsensus.quorumSignature.length() >= 3 * minQuorum(7))) { APIResponse.put("did", DID); From 96bd4023b59b78b2e4bf9b7dee37510627e97576 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 22 Mar 2022 13:14:16 +0530 Subject: [PATCH 031/179] receiver side logic for staking Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 16 +-- src/com/rubix/Constants/MiningConstants.java | 1 + .../rubix/TokenTransfer/TokenReceiver.java | 128 +++++++++++++++++- 3 files changed, 131 insertions(+), 14 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 9e7cb471..ed6d6b7d 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -25,15 +25,15 @@ public class StakeConsensus { public static Logger StakeConsensusLogger = Logger.getLogger(StakeConsensus.class); private static int socketTimeOut = 120000; - public static volatile JSONObject stakeDetails = new JSONObject(); private static volatile boolean STAKE_SUCCESS = false; - // mine ID - // QST_Height - // staker DID - // staked token hash - // sign on staking token - // sign on txn id - // sign on mining token + public static volatile JSONObject stakeDetails = new JSONObject(); + // MINE_ID + // QST_HEIGHT + // STAKED_QUORUM_DID + // STAKED_TOKEN + // STAKED_TOKEN_SIGN + // MINING_TID_SIGN + // MINED_RBT_SIGN // same object will be added to tokenchains of staked and mined token public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject data, IPFS ipfs, int PORT, diff --git a/src/com/rubix/Constants/MiningConstants.java b/src/com/rubix/Constants/MiningConstants.java index a06ed743..5b47c4d9 100644 --- a/src/com/rubix/Constants/MiningConstants.java +++ b/src/com/rubix/Constants/MiningConstants.java @@ -11,4 +11,5 @@ public class MiningConstants { public static final String MINING_TID_SIGN = "TIDSignature"; public static final String MINED_RBT_SIGN = "minedTokenSignature"; public static final String MINE_ID_SIGN = "mineIDSignature"; + public static final String QST_HEIGHT = "QSTHeight"; } \ No newline at end of file diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index feed78f0..f516e31a 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -42,6 +42,7 @@ import java.net.SocketException; import java.util.ArrayList; import java.util.Iterator; +import java.util.Random; import javax.imageio.ImageIO; @@ -359,6 +360,7 @@ public static String receive() { } } } + if (!chainFlag) { String errorMessage = "Broken Cheque Chain"; output.println("423"); @@ -390,24 +392,29 @@ public static String receive() { allTokensChains.put(partTokenChainContent.get(i)); JSONArray invalidTokens = new JSONArray(); - for (int i = 0; i < allTokensChains.length(); i++) { - JSONArray tokenChain = new JSONArray(allTokensChains.get(i).toString()); + + for (int count = 0; count < allTokensChains.length(); count++) { + + String tokens = null; + JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); TokenReceiverLogger.debug("Last Object = " + lastObject); + if (lastObject.has("owner")) { + TokenReceiverLogger.debug("Checking ownership"); String owner = lastObject.getString("owner"); - String tokens = allTokens.getString(i); + tokens = allTokens.getString(count); String hashString = tokens.concat(senderDidIpfsHash); String hashForPositions = calculateHash(hashString, "SHA3-256"); - String ownerIdentity = hashForPositions.concat(positionsArray.getString(i)); + String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); TokenReceiverLogger.debug("Ownership Here Sender Calculation"); TokenReceiverLogger.debug("tokens: " + tokens); TokenReceiverLogger.debug("hashString: " + hashString); TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positionsArray.getString(i)); + TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); @@ -415,8 +422,117 @@ public static String receive() { ownerCheck = false; invalidTokens.put(tokens); } - } + // ! staking checks (1..4) starts here + + // ! staking checks (1): Check incoming token level + String TokenContent = get(wholeTokens.getString(count), ipfs); + String tokenLevel = TokenContent.substring(0, 3); + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + int tokenNumber = 1200001; + + if (ownerCheck && (tokenChain.length() < tokenLevelValue) && (tokenLevelInt < 4) + && (tokenNumber > 1200000)) { + + // ! staking checks (2): For incoming new mint token, verify the staked token + + JSONObject secondObject = tokenChain.getJSONObject(1); + String stakedTokenTC = secondObject.getString("stakedToken"); + String stakedTokenSignTC = secondObject.getString("stakedTokenSignature"); + String stakerDIDTC = secondObject.getString("stakerDID"); + String stakerDIDSignTC = secondObject.getString("stakerDIDSignature"); + String mineIDTC = secondObject.getString("mineID"); + String mineIDSignTC = secondObject.getString("mineIDSignature"); + + String mineIDContent = get(mineIDTC, ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + String stakerDIDMineData = mineIDContentJSON.getString("stakerDID"); + String stakerDIDSignMineData = mineIDContentJSON.getString("stakerDID"); + String stakedTokenMineData = mineIDContentJSON.getString("stakedToken"); + String stakedTokenSignMineData = mineIDContentJSON.getString("stakedToken"); + + if (stakerDIDTC.equals(stakerDIDMineData) && stakedTokenTC.equals(stakedTokenMineData) + && stakedTokenSignTC.equals(stakedTokenSignMineData) + && stakerDIDSignTC.equals(stakerDIDSignMineData)) { + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakerDIDTC); + detailsToVerify.put("hash", mineIDTC); + detailsToVerify.put("signature", mineIDSignTC); + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + ArrayList ownersArray = new ArrayList(); + ownersArray = IPFSNetwork.dhtOwnerCheck(stakedTokenMineData); + + if (ownersArray.contains(stakerDIDTC)) { + TokenReceiverLogger.debug("Staking check passed: " + stakerDIDTC); + } else { + TokenReceiverLogger.debug( + "Staking check (2) failed - staked token " + stakedTokenMineData + + " is not owned by staker: " + + stakerDIDTC); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { + TokenReceiverLogger.debug( + "Staking check (2) failed - unable to verify mine ID signature by staker: " + + stakerDIDTC); + ownerCheck = false; + invalidTokens.put(tokens); + } + + TokenReceiverLogger + .debug("MineID Verification Successful with Staking node: " + stakerDIDTC); + } else { + TokenReceiverLogger.debug("Staking check (2) failed"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + // ! staking checks (3): Verify the signatures earned during the mining of the + // ! incoming mint token + JSONObject genesiObject = tokenChain.getJSONObject(0); + if (genesiObject.has("genesisSignatures")) { + + int randomNumber = new Random().nextInt(15); + String genesisSignatures = genesiObject.getString("genesisSignatures"); + String genesisSignaturesContent = get(genesisSignatures, ipfs); + JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); + JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); + if (VerificationPick.getString("hash") == genesiObject.getString("tid")) { + + if (Authenticate.verifySignature(VerificationPick.toString())) { + TokenReceiverLogger.debug("Staking check (3) successful"); + } else { + TokenReceiverLogger.debug( + "Staking check (3) failed: Could not verify genesis credit signature"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { + TokenReceiverLogger.debug( + "Staking check (3) failed: Genesis TID is not equal to the hash of the genesis signature"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { + TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not found"); + ownerCheck = false; + invalidTokens.put(tokens); + } + } + + } else if (lastObject.has("mineID")) { + TokenReceiverLogger.debug("Staking check (3) failed: Found staked token: " + tokens); + ownerCheck = false; + invalidTokens.put(tokens); + } + // ! staking checks ends here } if (!ownerCheck) { From 3f44f442f1e0fa95825f52c1aadd4f6f2649b0eb Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 22 Mar 2022 17:24:17 +0530 Subject: [PATCH 032/179] staked token check correction Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/ProofCredits.java | 5 +- .../rubix/TokenTransfer/TokenReceiver.java | 101 ++++++++++++------ 2 files changed, 74 insertions(+), 32 deletions(-) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 461f7484..84d4b0d4 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -417,7 +417,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONObject stakeDetails = StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, tokenChainGenesisObject, ipfs, SEND_PORT + 3, "alpha-stake-token"); - tokenChainArray.put(stakeDetails); + + if (stakeDetails.length() > 0) { + tokenChainArray.put(stakeDetails); + } writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index f516e31a..2126021a 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -425,6 +425,40 @@ public static String receive() { // ! staking checks (1..4) starts here + // ! staking checks (3): Verify the signatures earned during the mining of the + // ! incoming mint token + JSONObject genesiObject = tokenChain.getJSONObject(0); + if (genesiObject.has("genesisSignatures")) { + + int randomNumber = new Random().nextInt(15); + String genesisSignatures = genesiObject.getString("genesisSignatures"); + String genesisSignaturesContent = get(genesisSignatures, ipfs); + JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); + JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); + if (VerificationPick.getString("hash") == genesiObject.getString("tid")) { + + if (Authenticate.verifySignature(VerificationPick.toString())) { + TokenReceiverLogger.debug("Staking check (3) successful"); + } else { + TokenReceiverLogger.debug( + "Staking check (3) failed: Could not verify genesis credit signature"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { + TokenReceiverLogger.debug( + "Staking check (3) failed: Genesis TID is not equal to the hash of the genesis signature"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { + TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not found"); + ownerCheck = false; + invalidTokens.put(tokens); + } + // ! staking checks (1): Check incoming token level String TokenContent = get(wholeTokens.getString(count), ipfs); String tokenLevel = TokenContent.substring(0, 3); @@ -491,46 +525,49 @@ public static String receive() { ownerCheck = false; invalidTokens.put(tokens); } + } - // ! staking checks (3): Verify the signatures earned during the mining of the - // ! incoming mint token - JSONObject genesiObject = tokenChain.getJSONObject(0); - if (genesiObject.has("genesisSignatures")) { + } else if (lastObject.has("mineID")) { - int randomNumber = new Random().nextInt(15); - String genesisSignatures = genesiObject.getString("genesisSignatures"); - String genesisSignaturesContent = get(genesisSignatures, ipfs); - JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); - JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); - if (VerificationPick.getString("hash") == genesiObject.getString("tid")) { + String mineID = lastObject.getString("mineID"); + String mineIDContent = get(mineID, ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + String stakerDID = mineIDContentJSON.getString("stakerDID"); + String stakerDIDSign = mineIDContentJSON.getString("stakerDIDSignature"); + String stakedToken = mineIDContentJSON.getString("stakedToken"); + String stakedTokenSign = mineIDContentJSON.getString("stakedTokenSignature"); - if (Authenticate.verifySignature(VerificationPick.toString())) { - TokenReceiverLogger.debug("Staking check (3) successful"); - } else { - TokenReceiverLogger.debug( - "Staking check (3) failed: Could not verify genesis credit signature"); - ownerCheck = false; - invalidTokens.put(tokens); - } + JSONObject StakerToVerify = new JSONObject(); + StakerToVerify.put("did", senderDidIpfsHash); + StakerToVerify.put("hash", stakerDID); + StakerToVerify.put("signature", stakerDIDSign); - } else { - TokenReceiverLogger.debug( - "Staking check (3) failed: Genesis TID is not equal to the hash of the genesis signature"); - ownerCheck = false; - invalidTokens.put(tokens); - } + JSONObject tokenToVerify = new JSONObject(); + tokenToVerify.put("did", senderDidIpfsHash); + tokenToVerify.put("hash", stakedToken); + tokenToVerify.put("signature", stakedTokenSign); + if (Authenticate.verifySignature(StakerToVerify.toString()) + && Authenticate.verifySignature(tokenToVerify.toString())) { + + ArrayList ownersArray = new ArrayList(); + ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + + if (ownersArray.contains(senderDidIpfsHash)) { } else { - TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not found"); + TokenReceiverLogger.debug( + "Staking check failed - staked token " + stakedToken + " is not owned by staker: " + + senderDidIpfsHash); ownerCheck = false; invalidTokens.put(tokens); } - } - } else if (lastObject.has("mineID")) { - TokenReceiverLogger.debug("Staking check (3) failed: Found staked token: " + tokens); - ownerCheck = false; - invalidTokens.put(tokens); + } else { + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to verify staked token height"); + ownerCheck = false; + invalidTokens.put(tokens); + } } // ! staking checks ends here } @@ -993,7 +1030,9 @@ public static String receive() { 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(); From fff80bcdaa0a0edfa43851ca0b2025f21137ab16 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 22 Mar 2022 18:02:31 +0530 Subject: [PATCH 033/179] debug stats staking signs Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index ed6d6b7d..8c1ade65 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -141,7 +141,7 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON try { qResponse[j] = qIn[j].readLine(); StakeConsensusLogger - .debug("Received stake token signatures. Sending Credits"); + .debug("Received stake token signatures: " + qResponse[j]); } catch (SocketException e) { StakeConsensusLogger .debug("Token Details validation failed. Received null response"); From 134f518d32170b97232743a18c2dc054f0455af9 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 23 Mar 2022 12:38:24 +0530 Subject: [PATCH 034/179] minted token level check Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 70 +++++++++++++++++-- src/com/rubix/Consensus/StakeConsensus.java | 56 ++++++++++++--- .../rubix/TokenTransfer/TokenReceiver.java | 25 +++---- 3 files changed, 122 insertions(+), 29 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index f72471a5..461d3e02 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -27,6 +27,7 @@ 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; @@ -44,6 +45,7 @@ import java.net.URL; import java.text.ParseException; import java.util.HashSet; +import java.util.Random; import javax.imageio.ImageIO; @@ -138,14 +140,72 @@ public void run() { executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - QuorumConsensusLogger.debug("Validating new token details..."); + JSONObject genesisBlock = new JSONObject(response); + QuorumConsensusLogger.debug("Validating new token details: " + genesisBlock); + System.out.println(genesisBlock); - boolean isValid = true; + boolean isValid = false; // ! check token is in same level + String TokenContent = get(genesisBlock.getString("tokenHash"), ipfs); + String tokenLevel = TokenContent.substring(0, 3); + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + + String GET_URL_credit = SYNC_IP + "/getlevel"; + URL URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + QuorumConsensusLogger.debug("response from service " + response_credit.toString()); + JSONObject resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + int creditsRequired = (int) Math.pow(2, (2 + level_credit)); + + if (level_credit == tokenLevelInt) { + + QuorumConsensusLogger.debug("Validated level of newly minted token"); + isValid = true; + } + + } else + QuorumConsensusLogger.debug("GET request not worked"); + // ! validate mined token hash and ownership - JSONObject genesisBlock = new JSONObject(response); - System.out.println(genesisBlock); + if (genesisBlock.has("quorumSignatures")) { + + int randomNumber = new Random().nextInt(15); + String genesisSignatures = genesisBlock.getString("quorumSignatures"); + String genesisSignaturesContent = get(genesisSignatures, ipfs); + JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); + JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); + if (VerificationPick.getString("hash") == genesisBlock.getString("tid")) { + + if (Authenticate.verifySignature(VerificationPick.toString())) { + + QuorumConsensusLogger.debug("Validated signature of newly minted token"); + isValid = true; + } else { + QuorumConsensusLogger.debug("Signature not verified"); + isValid = false; + } + + } else { + QuorumConsensusLogger.debug("Mined token quorum signature hash not matched"); + isValid = false; + } + + } if (isValid) { @@ -201,8 +261,6 @@ public void run() { JSONObject stakingSigns = new JSONObject(); - genesisBlock.put("stakingToken", tokenHash); - stakingSigns.put( STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 8c1ade65..60a55832 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -1,5 +1,8 @@ package com.rubix.Consensus; +import static com.rubix.Constants.MiningConstants.MINE_ID; +import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; +import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.LOGGER_PATH; import static com.rubix.Resources.Functions.calculateHash; @@ -14,6 +17,10 @@ import java.io.PrintStream; import java.net.Socket; import java.net.SocketException; +import java.util.ArrayList; + +import com.rubix.AuthenticateNode.Authenticate; +import com.rubix.Resources.IPFSNetwork; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; @@ -32,6 +39,7 @@ public class StakeConsensus { // STAKED_QUORUM_DID // STAKED_TOKEN // STAKED_TOKEN_SIGN + // MINE_ID_SIGN // MINING_TID_SIGN // MINED_RBT_SIGN // same object will be added to tokenchains of staked and mined token @@ -88,10 +96,11 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON qResponse[j] = qIn[j].readLine(); } catch (SocketException e) { StakeConsensusLogger.debug("Token Details validation failed. Received null response"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } if (!qResponse[j].contains("44")) { - StakeConsensusLogger.debug("Token Details validated. Received stake token details.."); + StakeConsensusLogger.debug("Token Details validated. Received staked token details.."); Boolean ownerCheck = false; String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", quorumPID[j]); @@ -103,7 +112,7 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON // ! check ownership of stakeTC from Token Receiver logic - if (stakeTC.length() != 0 && stakeTokenHash != null && positionsArray != null) { + if (stakeTC.length() > 0 && stakeTokenHash != null && positionsArray != null) { JSONObject lastObject = stakeTC.getJSONObject(stakeTCObject.length() - 1); StakeConsensusLogger.debug("Last Object = " + lastObject); if (lastObject.has("owner")) { @@ -126,14 +135,16 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON if (!owner.equals(ownerRecalculated)) { ownerCheck = false; StakeConsensusLogger.debug("Ownership Check Failed"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } } else { StakeConsensusLogger.debug("insufficient stake token height details"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } if (ownerCheck && !STAKE_SUCCESS) { - StakeConsensusLogger.debug("Ownership Check Success"); + StakeConsensusLogger.debug("Ownership Check Success for: PID" + quorumPID[j]); STAKE_SUCCESS = true; qOut[j].println("alpha-stake-token-verified"); StakeConsensusLogger.debug("Waiting for stake signatures"); @@ -149,30 +160,53 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON if (!qResponse[j].contains("44")) { - // ! valodate signatures - StakeConsensusLogger.debug("Validating Signatures"); - // ! add mine signs to tokenchain StakeConsensusLogger.debug("Adding mine signatures"); JSONObject mineSigns = new JSONObject(qResponse[j]); stakeDetails = mineSigns; - stakeDetails.put("stakedToken", stakeTokenHash); + String quorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", + quorumPID[j]); - // ! send credits - StakeConsensusLogger.debug("Sending Credits"); + // ! validate signatures + StakeConsensusLogger.debug("Validating Signatures"); + JSONObject mineIDSign = new JSONObject(); + mineIDSign.put("did", stakeDetails.getString(quorumDID)); + mineIDSign.put("hash", stakeDetails.getString(MINE_ID)); + mineIDSign.put("signature", stakeDetails.getString(MINE_ID_SIGN)); + boolean mineSignCheck = Authenticate.verifySignature(mineIDSign.toString()); + + ArrayList ownersArray = new ArrayList(); + ownersArray = IPFSNetwork.dhtOwnerCheck(MINE_ID); + + if (ownersArray.contains(STAKED_QUORUM_DID)) { + StakeConsensusLogger.debug("Staking pin check passed: " + stakeDetails + .getString(STAKED_QUORUM_DID)); + } else { + StakeConsensusLogger.debug("Staking pin check failed: " + stakeDetails + .getString(STAKED_QUORUM_DID)); + } + + if (mineSignCheck) { + // ! send credits + StakeConsensusLogger.debug( + "%%%%%%%%||||||||||||########--Staking Complete! Sending Credits--###########|||||||||||||%%%%%%%%%%%"); + + qOut[j].println("staking-completed"); + } - qOut[j].println("staking-success"); } } else { StakeConsensusLogger.debug("Ownership Check Failed"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } else if (qResponse[j].equals("444")) { StakeConsensusLogger.debug("Error response from staker (insuff). Skipping..."); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("445")) { - + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 2126021a..3b17fc88 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -431,7 +431,7 @@ public static String receive() { if (genesiObject.has("genesisSignatures")) { int randomNumber = new Random().nextInt(15); - String genesisSignatures = genesiObject.getString("genesisSignatures"); + String genesisSignatures = genesiObject.getString("quorumSignatures"); String genesisSignaturesContent = get(genesisSignatures, ipfs); JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); @@ -550,17 +550,18 @@ public static String receive() { if (Authenticate.verifySignature(StakerToVerify.toString()) && Authenticate.verifySignature(tokenToVerify.toString())) { - ArrayList ownersArray = new ArrayList(); - ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); - - if (ownersArray.contains(senderDidIpfsHash)) { - } else { - TokenReceiverLogger.debug( - "Staking check failed - staked token " + stakedToken + " is not owned by staker: " - + senderDidIpfsHash); - ownerCheck = false; - invalidTokens.put(tokens); - } + // ArrayList ownersArray = new ArrayList(); + // ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + + // if (ownersArray.contains(senderDidIpfsHash)) { + // } else { + // TokenReceiverLogger.debug( + // "Staking check failed - staked token " + stakedToken + " is not owned by + // staker: " + // + senderDidIpfsHash); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } } else { TokenReceiverLogger.debug( From 9cb610390b48149f7eaa920dc25ae2a1c1219950 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 23 Mar 2022 13:40:06 +0530 Subject: [PATCH 035/179] staking error messages Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 30 ++++++++++++-------- src/com/rubix/Consensus/StakeConsensus.java | 10 +++---- src/com/rubix/Mining/ProofCredits.java | 15 ++++++++-- 3 files changed, 35 insertions(+), 20 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 461d3e02..c679509a 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -186,23 +186,29 @@ public void run() { int randomNumber = new Random().nextInt(15); String genesisSignatures = genesisBlock.getString("quorumSignatures"); - String genesisSignaturesContent = get(genesisSignatures, ipfs); - JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); - JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); - if (VerificationPick.getString("hash") == genesisBlock.getString("tid")) { + try { + String genesisSignaturesContent = get(genesisSignatures, ipfs); + JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); + JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); + if (VerificationPick.getString("hash") == genesisBlock.getString("tid")) { - if (Authenticate.verifySignature(VerificationPick.toString())) { + if (Authenticate.verifySignature(VerificationPick.toString())) { + + QuorumConsensusLogger.debug("Validated signature of newly minted token"); + isValid = true; + } else { + QuorumConsensusLogger.debug("Signature not verified"); + isValid = false; + } - QuorumConsensusLogger.debug("Validated signature of newly minted token"); - isValid = true; } else { - QuorumConsensusLogger.debug("Signature not verified"); + QuorumConsensusLogger.debug("Mined token quorum signature hash not matched"); isValid = false; } - - } else { - QuorumConsensusLogger.debug("Mined token quorum signature hash not matched"); - isValid = false; + } catch (Exception e) { + QuorumConsensusLogger + .debug("Mined token quorum signature hash not found in IPFS. Skipping..."); + // isValid = false; } } diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 60a55832..bd8a4dde 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -44,7 +44,7 @@ public class StakeConsensus { // MINED_RBT_SIGN // same object will be added to tokenchains of staked and mined token - public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject data, IPFS ipfs, int PORT, + public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject data, IPFS ipfs, int PORT, String operation) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -101,7 +101,7 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON if (!qResponse[j].contains("44")) { StakeConsensusLogger.debug("Token Details validated. Received staked token details.."); - Boolean ownerCheck = false; + Boolean ownerCheck = true; String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", quorumPID[j]); JSONArray stakeTokenArray = new JSONArray(qResponse[j]); @@ -207,6 +207,9 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("445")) { IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + } else { + StakeConsensusLogger.debug("Error response from staker. Skipping..."); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } @@ -219,12 +222,9 @@ public static JSONObject getStakeConsensus(JSONArray signedAphaQuorumArray, JSON } ; - return stakeDetails; - } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); } - return stakeDetails; } } diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 84d4b0d4..3d86c9d7 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -414,12 +414,21 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainArray.put(tokenChainGenesisObject); // ! new token will now need a staked token - JSONObject stakeDetails = StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, + StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, tokenChainGenesisObject, ipfs, SEND_PORT + 3, "alpha-stake-token"); - if (stakeDetails.length() > 0) { - tokenChainArray.put(stakeDetails); + if (StakeConsensus.stakeDetails.length() > 0) { + tokenChainArray.put(StakeConsensus.stakeDetails); + } else { + updateQuorum(quorumArray, null, false, type); + APIResponse.put("did", DID); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", + "Staking failed.. Retry with alpha quorum members with aleast 1 RBT balance"); + ProofCreditsLogger.warn("Staking failed"); + return APIResponse; } writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); From f3f5e9281eba82235da38583724c03601a9d975b Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 23 Mar 2022 20:54:28 +0530 Subject: [PATCH 036/179] ipfs content in tokenchain block Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 10 ++++------ src/com/rubix/Consensus/StakeConsensus.java | 10 ++++++---- src/com/rubix/Mining/ProofCredits.java | 2 ++ src/com/rubix/TokenTransfer/TokenReceiver.java | 4 ++++ 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index c679509a..d7de7617 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -27,7 +27,6 @@ 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; @@ -147,7 +146,7 @@ public void run() { boolean isValid = false; // ! check token is in same level - String TokenContent = get(genesisBlock.getString("tokenHash"), ipfs); + String TokenContent = genesisBlock.getString("tokenContent"); String tokenLevel = TokenContent.substring(0, 3); int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); @@ -185,11 +184,10 @@ public void run() { if (genesisBlock.has("quorumSignatures")) { int randomNumber = new Random().nextInt(15); - String genesisSignatures = genesisBlock.getString("quorumSignatures"); + JSONArray genesisSignatures = genesisBlock.getJSONArray("quorumSignContent"); try { - String genesisSignaturesContent = get(genesisSignatures, ipfs); - JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); - JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); + + JSONObject VerificationPick = genesisSignatures.getJSONObject(randomNumber); if (VerificationPick.getString("hash") == genesisBlock.getString("tid")) { if (Authenticate.verifySignature(VerificationPick.toString())) { diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index bd8a4dde..34837cd5 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -90,17 +90,19 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject if (operation.equals("alpha-stake-token")) { qOut[j].println(data.toString()); - StakeConsensusLogger.debug("Token Details sent for validation..."); + StakeConsensusLogger.debug("Mined Token Details sent for validation..."); try { qResponse[j] = qIn[j].readLine(); } catch (SocketException e) { - StakeConsensusLogger.debug("Token Details validation failed. Received null response"); + StakeConsensusLogger + .debug("Mined Token Details validation failed. Received null response"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } if (!qResponse[j].contains("44")) { - StakeConsensusLogger.debug("Token Details validated. Received staked token details.."); + StakeConsensusLogger + .debug("Mined Token Details validated. Received staked token details.."); Boolean ownerCheck = true; String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", quorumPID[j]); @@ -155,7 +157,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .debug("Received stake token signatures: " + qResponse[j]); } catch (SocketException e) { StakeConsensusLogger - .debug("Token Details validation failed. Received null response"); + .debug("Mined Token Details validation failed. Received null response"); } if (!qResponse[j].contains("44")) { diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 3d86c9d7..1a41327a 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -400,6 +400,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONArray tokenChainArray = new JSONArray(); JSONObject tokenChainGenesisObject = new JSONObject(); tokenChainGenesisObject.put("quorumSignatures", credit); + tokenChainGenesisObject.put("quorumSignContent", InitiatorConsensus.quorumSignature); tokenChainGenesisObject.put("sender", DID); tokenChainGenesisObject.put("comment", "Mining-Genesis"); tokenChainGenesisObject.put("tid", tid); @@ -407,6 +408,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject.put("blockNumber", 0); tokenChainGenesisObject.put("QSTHeight", QSTHeight); tokenChainGenesisObject.put("tokenHash", tokenHash); + tokenChainGenesisObject.put("tokenContent", token.getString(i)); tokenChainGenesisObject.put("nextHash", calculateHash(tid, "SHA3-256")); tokenChainGenesisObject.put("previousHash", ""); // stakingData = tokenChainGenesisObject; diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 3b17fc88..b139d0a5 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -569,6 +569,10 @@ public static String receive() { ownerCheck = false; invalidTokens.put(tokens); } + } else if (lastObject.length() == 0) { + TokenReceiverLogger.debug("Staking check failed: No Token Chain data found for token: " + tokens); + // ownerCheck = false; + // invalidTokens.put(tokens); } // ! staking checks ends here } From bc8725ca9528420b2e8f0a154253b86a8b3b6f97 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 24 Mar 2022 00:44:30 +0530 Subject: [PATCH 037/179] rec check update Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index b139d0a5..9eec6f97 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -431,8 +431,8 @@ public static String receive() { if (genesiObject.has("genesisSignatures")) { int randomNumber = new Random().nextInt(15); - String genesisSignatures = genesiObject.getString("quorumSignatures"); - String genesisSignaturesContent = get(genesisSignatures, ipfs); + String genesisSignaturesContent = genesiObject.getString("quorumSigContent"); + // String genesisSignaturesContent = get(genesisSignatures, ipfs); JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); if (VerificationPick.getString("hash") == genesiObject.getString("tid")) { From 88fd669cdac99e8e2274f0edb0ea6b50a5c74244 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 24 Mar 2022 11:40:31 +0530 Subject: [PATCH 038/179] fix debug statement in quorum consensus Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index d7de7617..bd102c73 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -409,7 +409,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", } } else { - QuorumConsensusLogger.debug("Token Staking Failed: Token to stake not found"); + QuorumConsensusLogger.debug("Token Staking Failed: Insufficient Balance to Stake!"); out.println("445"); socket.close(); serverSocket.close(); From 080a94fa0eb5833683d166c450258880171f7148 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 24 Mar 2022 12:18:05 +0530 Subject: [PATCH 039/179] token-authenticity merge Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Ping/GetCredits.java | 79 ++++++ src/com/rubix/Ping/PingReceive.java | 2 + src/com/rubix/Ping/QuorumPingReceive.java | 19 +- src/com/rubix/Resources/APIHandler.java | 102 ++++++- src/com/rubix/Resources/FractionChooser.java | 88 ++++++ src/com/rubix/Resources/Functions.java | 245 +++++++++++------ src/com/rubix/Resources/IntegrityCheck.java | 22 +- .../rubix/TokenTransfer/TokenReceiver.java | 251 ++++++++++++------ src/com/rubix/TokenTransfer/TokenSender.java | 38 ++- 9 files changed, 666 insertions(+), 180 deletions(-) create mode 100644 src/com/rubix/Ping/GetCredits.java create mode 100644 src/com/rubix/Resources/FractionChooser.java diff --git a/src/com/rubix/Ping/GetCredits.java b/src/com/rubix/Ping/GetCredits.java new file mode 100644 index 00000000..018feeea --- /dev/null +++ b/src/com/rubix/Ping/GetCredits.java @@ -0,0 +1,79 @@ +package com.rubix.Ping; + +import io.ipfs.api.IPFS; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.Socket; +import java.net.SocketException; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.IPFSNetwork.*; + +public class GetCredits { + private static final Logger PingSenderLogger = Logger.getLogger(GetCredits.class); + public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + + public static JSONObject Contact(String did, int port) throws IOException, JSONException { + repo(ipfs); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + String peerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", did); + + JSONObject APIResponse = new JSONObject(); + + String appName = peerID.concat("Ping"); + forward(appName, port, peerID); + PingSenderLogger.debug("Forwarded to " + appName + " on " + port + " for collecting credits"); + Socket senderSocket = new Socket("127.0.0.1", port); + + BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); + PrintStream output = new PrintStream(senderSocket.getOutputStream()); + + output.println("Get-Credits"); +// PingSenderLogger.debug("Sent Credits request"); + + String pongResponse; + try { + pongResponse = input.readLine(); + } catch (SocketException e) { + PingSenderLogger.warn("Quorum " + did + " is unable to Respond! - Credits Ping"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Quorum " + did + "is unable to respond! - Credits Ping"); + + return APIResponse; + } + + + if (pongResponse == null) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); +// PingSenderLogger.info("Credits response not received"); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Credits response not received"); + + }else { + PingSenderLogger.info("Credits received from " + did); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Success"); + APIResponse.put("message", Integer.parseInt(pongResponse)); + + } + return APIResponse; + } +} diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index de4a0cf0..637dc3b0 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -96,6 +96,8 @@ public static String receive(int port) throws JSONException { } catch (IOException e) { e.printStackTrace(); + } catch (JSONException e) { + e.printStackTrace(); } return APIResponse.toString(); } diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java index 354315df..6abdbda2 100644 --- a/src/com/rubix/Ping/QuorumPingReceive.java +++ b/src/com/rubix/Ping/QuorumPingReceive.java @@ -83,7 +83,22 @@ public static String receive(int port) throws JSONException { APIResponse.put("message", "Pong Sent"); QuorumPingReceiverLogger.info("Pong Sent"); - } else { + }if(pingRequest != null && pingRequest.contains("Get-Credits")) { + String qstFile = WALLET_DATA_PATH.concat("QuorumSignedTransactions.json"); + File quorumFile = new File(qstFile); + int unspentCredits = 0; + if(quorumFile.exists()){ + String qFile = readFile(qstFile); + JSONArray qArray = new JSONArray(qFile); + unspentCredits = qArray.length(); + } + output.println(unspentCredits); + + APIResponse.put("status", "Success"); + APIResponse.put("message", "Credits Sent"); + QuorumPingReceiverLogger.info("Credits Sent " + unspentCredits); + + }else{ APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong Failed"); QuorumPingReceiverLogger.info("Pong Failed"); @@ -96,6 +111,8 @@ public static String receive(int port) throws JSONException { } catch (IOException e) { e.printStackTrace(); + } catch (JSONException e) { + e.printStackTrace(); } return APIResponse.toString(); } diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 466442dc..d1d929b1 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -59,6 +59,37 @@ public class APIHandler { * @throws IOException handles IO Exceptions */ + public static JSONObject sortType2Quorum() { + Functions.pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + JSONObject sendMessage = new JSONObject(); + JSONArray quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + APILogger.debug("Before Sorting: " + quorumArray); + int code = 0; + try { + code = arrangeQuorum(quorumArray, SEND_PORT + 11, 0); + } catch (IOException e) { + APILogger.debug("Credits failed"); + } + + if (code == 200) { + quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + APILogger.debug("After Sorting: " + quorumArray); + sendMessage.put("status", "Success"); + sendMessage.put("message", "Sorted"); + } else if (code == 401) { + APILogger.debug("Could not collect all(min. 21) credits"); + sendMessage.put("status", "Failed"); + sendMessage.put("message", ""); + } else if (code == 402) { + APILogger.debug("7 alpha node credits not summing up to requested amount"); + sendMessage.put("status", "Failed"); + sendMessage.put("message", ""); + } + + return sendMessage; + + } public static JSONObject send(String data) throws Exception { Functions.pathSet(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -134,6 +165,70 @@ public static JSONObject create(int type) throws Exception { return sendMessage; } + /** + * Utility function to add token ownership + */ + public static JSONObject addOwnership() throws IOException { + pathSet(); + String wholeToken = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray wholeTokensArray = new JSONArray(wholeToken); + String partsToken; + JSONArray partsTokenArray = new JSONArray(); + boolean parts = false; + if (new File(PAYMENTS_PATH.concat("PartsToken.json")).exists()) { + partsToken = readFile(PAYMENTS_PATH.concat("PartsToken.json")); + partsTokenArray = new JSONArray(partsToken); + parts = true; + } + JSONArray allTokens = new JSONArray(); + for (int i = 0; i < wholeTokensArray.length(); i++) + allTokens.put(wholeTokensArray.getString(i)); + + if (parts) { + for (int i = 0; i < partsTokenArray.length(); i++) + allTokens.put(partsTokenArray.getString(i)); + } + + String didFile = readFile(DATA_PATH.concat("DID.json")); + JSONArray didArray = new JSONArray(didFile); + String did = didArray.getJSONObject(0).getString("didHash"); + + for (int i = 0; i < allTokens.length(); i++) { + String tokens = allTokens.getString(i); + String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokens).concat(".json")); + JSONArray tokenChainArray = new JSONArray(tokenChain); + JSONObject lastObject = tokenChainArray.getJSONObject(tokenChainArray.length() - 1); + if (!lastObject.has("owner")) { + String hashString = tokens.concat(did); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + + BufferedImage pvt = ImageIO.read(new File(DATA_PATH.concat(did).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(pvt); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + String ownerIdentity = hashForPositions.concat(positions); + String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); + lastObject.put("owner", ownerIdentityHash); + } + tokenChainArray.remove(tokenChainArray.length() - 1); + tokenChainArray.put(lastObject); + writeToFile(TOKENCHAIN_PATH.concat(tokens).concat(".json"), tokenChainArray.toString(), false); + + } + + JSONObject sendMessage = new JSONObject(); + sendMessage.put("did", did); + sendMessage.put("tid", "null"); + sendMessage.put("status", "Success"); + sendMessage.put("message", "Ownership Added"); + return sendMessage; + + } + /** * A method to add and host your DID ans Public share to ipfs * @@ -199,9 +294,10 @@ public static JSONObject creditsInfo() throws JSONException { File quorumFile = new File(qstFile); File minedFile = new File(mineFile); - + JSONObject returnObject = new JSONObject(); int spentCredits = 0; int unspentCredits = 0; + try { if (quorumFile.exists()) { String qFile = readFile(qstFile); JSONArray qArray = new JSONArray(qFile); @@ -213,9 +309,11 @@ public static JSONObject creditsInfo() throws JSONException { spentCredits = mArray.length(); } - JSONObject returnObject = new JSONObject(); returnObject.put("spentCredits", spentCredits); returnObject.put("unspentCredits", unspentCredits); + } catch (JSONException e) { + // TODO: handle exception + } return returnObject; } diff --git a/src/com/rubix/Resources/FractionChooser.java b/src/com/rubix/Resources/FractionChooser.java new file mode 100644 index 00000000..4f328c6c --- /dev/null +++ b/src/com/rubix/Resources/FractionChooser.java @@ -0,0 +1,88 @@ +package com.rubix.Resources; + + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import org.apache.log4j.*; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import static com.rubix.Resources.Functions.*; + +public class FractionChooser { + public static String output; + + public static JSONArray tokenHeader; + + public static Logger FractionChooserLogger = Logger.getLogger(FractionChooser.class); + + public static JSONArray calculate(int amount) { + JSONArray tokensList = new JSONArray(); + tokenHeader = new JSONArray(); + JSONObject tknmap = new JSONObject(); + try { + int index = 0; + LinkedHashMap map = new LinkedHashMap<>(); + LinkedHashMap usedmap = new LinkedHashMap<>(); + List bnk = new ArrayList<>(); + if (amount < 1) { + FractionChooserLogger.warn("Invalid Transaction Amount"); + output = "Please make a valid transaction"; + return tokensList; + } + JSONArray mapList = new JSONArray(readFile(PAYMENTS_PATH + "TokenMap.json")); + int i; + for (i = 0; i < mapList.length(); i++) { + JSONObject tempJsonObject = mapList.getJSONObject(i); + String type = tempJsonObject.getString("type"); + int valueInt = tempJsonObject.getInt("value"); + tknmap.put(String.valueOf(valueInt), type); + String lists = readFile(PAYMENTS_PATH + tempJsonObject.getString("type") + ".json"); + JSONArray tempJsonArray = new JSONArray(lists); + bnk.add(i, tempJsonArray); + int size = tempJsonArray.length(); + map.put(Integer.valueOf(valueInt), Integer.valueOf(size)); + usedmap.put(Integer.valueOf(valueInt), Integer.valueOf(0)); + } + List keyList = new ArrayList(map.keySet()); + for (i = map.size() - 1; i > 0; i--) { + if (((Integer)keyList.get(i)).intValue() <= amount) { + index = i; + break; + } + } + while (amount != 0) { + int valueInt = ((Integer)keyList.get(index)).intValue(); + if (((Integer)map.get(Integer.valueOf(valueInt))).intValue() > 0 && valueInt <= amount) { + amount -= valueInt; + int temp = ((Integer)usedmap.get(Integer.valueOf(valueInt))).intValue(); + int temp1 = ((Integer)map.get(Integer.valueOf(valueInt))).intValue(); + usedmap.put(Integer.valueOf(valueInt), Integer.valueOf(++temp)); + map.put(Integer.valueOf(valueInt), Integer.valueOf(--temp1)); + } else if (index != 0) { + index--; + } else { + FractionChooserLogger.warn("Insufficient Amount in the Wallet. Required " + amount + " currency"); + output = "Balance not sufficient, need " + amount + " more currency"; + return tokensList; + } + if (valueInt > amount && index != 0) + index--; + } + for (i = 0; i < keyList.size(); i++) { + for (int j = 0; j < ((Integer)usedmap.get(keyList.get(i))).intValue(); j++) { + tokensList.put(((JSONArray)bnk.get(i)).getJSONObject(j).getString("tokenHash")); + tokenHeader.put(tknmap.get(String.valueOf(keyList.get(i)))); + } + } + } catch (JSONException e) { + FractionChooserLogger.error("JSON Exception Occurred", (Throwable)e); + e.printStackTrace(); + } + FractionChooserLogger.debug("Tokens chosen to be sent: " + tokensList); + return tokensList; + } +} + diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 7a702ac6..f38f978c 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -32,10 +32,13 @@ import java.util.ArrayList; import java.util.Date; import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; import javax.imageio.ImageIO; import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Ping.GetCredits; import com.rubix.Ping.PingCheck; import org.apache.log4j.Logger; @@ -918,7 +921,7 @@ public static String mineToken(int level, int tokenNumber) { String levelHex = Integer.toHexString(level); if (level < 16) levelHex = String.valueOf(0).concat(levelHex); - String token = String.valueOf(0) + levelHex + tokenHash; + String token = 0 + levelHex + tokenHash; return token; } @@ -940,10 +943,7 @@ public static String toBinary(int x, int len) { 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; + return getValues(file.getAbsolutePath(), "senderdid", "consensusID", consensusID).equals(""); } else return true; } @@ -1184,6 +1184,7 @@ public static void correctPartToken() throws JSONException { public static void tokenBank() throws JSONException { pathSet(); String bank = readFile(PAYMENTS_PATH.concat("BNK00.json")); + try { JSONArray bankArray = new JSONArray(bank); ArrayList bankDuplicates = new ArrayList<>(); @@ -1205,7 +1206,7 @@ public static void tokenBank() throws JSONException { } File tokensPath = new File(TOKENS_PATH); - String contents[] = tokensPath.list(); + String[] contents = tokensPath.list(); ArrayList tokenFiles = new ArrayList(); for (int i = 0; i < contents.length; i++) { if (!contents[i].contains("PARTS")) @@ -1216,6 +1217,9 @@ public static void tokenBank() throws JSONException { if (!bankDuplicates.contains(tokenFiles.get(i).toString())) deleteFile(TOKENS_PATH.concat(tokenFiles.get(i).toString())); } + } catch (JSONException e) { + // TODO: handle exception + } } @@ -1453,6 +1457,7 @@ public static Double formatAmount(Double amount) { public static void clearParts() throws JSONException { String partsFile = readFile(PAYMENTS_PATH.concat("PartsToken.json")); + try { JSONArray partsArray = new JSONArray(partsFile); for (int i = 0; i < partsArray.length(); i++) { if (partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) <= 0.000 @@ -1462,6 +1467,9 @@ public static void clearParts() throws JSONException { } } writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partsArray.toString(), false); + } catch (JSONException e) { + // TODO: handle exception + } } public static void backgroundChecks() { @@ -1486,27 +1494,27 @@ public static void backgroundChecks() { public static String sanityMessage; - public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOException, JSONException { - FunctionsLogger.info("Entering SanityCheck"); + public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOException { + // FunctionsLogger.info("Entering SanityCheck"); boolean sanityCheckErrorFlag = true; if (sanityCheckErrorFlag && checkIPFSStatus(peerid, ipfs)) { FunctionsLogger.debug("IPFS is working in " + peerid); - FunctionsLogger.debug("IPFS check true"); + // FunctionsLogger.debug("IPFS check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("IPFS is not working in " + peerid); - FunctionsLogger.debug("IPFS check false"); + // FunctionsLogger.debug("IPFS is not working in " + peerid); + // FunctionsLogger.debug("IPFS check false"); sanityMessage = "IPFS is not working in " + peerid; } if (sanityCheckErrorFlag) { if (bootstrapConnect(peerid, ipfs)) { FunctionsLogger.debug("Bootstrap connected for " + peerid); - FunctionsLogger.debug("Bootstrap check true"); + // FunctionsLogger.debug("Bootstrap check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Bootstrap connection unsuccessful for " + peerid); - FunctionsLogger.debug("Bootstrap check false"); + // FunctionsLogger.debug("Bootstrap connection unsuccessful for " + peerid); + // FunctionsLogger.debug("Bootstrap check false"); sanityMessage = "Bootstrap connection unsuccessful for " + peerid; } } @@ -1514,22 +1522,22 @@ public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOE if (sanityCheckErrorFlag) { if (ping(peerid, port)) { FunctionsLogger.debug("Jar is running as expected in " + peerid); - FunctionsLogger.debug("Jar check true"); + // FunctionsLogger.debug("Jar check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Jar is not running in " + peerid); - FunctionsLogger.debug("Jar check false"); + // FunctionsLogger.debug("Jar is not running in " + peerid); + // FunctionsLogger.debug("Jar check false"); sanityMessage = "Jar is not running in " + peerid; } } if (sanityCheckErrorFlag) { if (portCheckAndKill(port)) { - FunctionsLogger.debug("Ports are available for transcations in " + peerid); - FunctionsLogger.debug("Ports check true"); + FunctionsLogger.debug("Ports are available for transactions in " + peerid); + // FunctionsLogger.debug("Ports check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Ports are not available for " + peerid); - FunctionsLogger.debug("Ports check false"); + // FunctionsLogger.debug("Ports are not available for " + peerid); + // FunctionsLogger.debug("Ports check false"); sanityMessage = "Ports are not available for " + peerid; } } @@ -1538,35 +1546,97 @@ public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOE } public static boolean checkIPFSStatus(String peerid, IPFS ipfs) { - FunctionsLogger.info("Entering checkIPFSStatus"); + // FunctionsLogger.info("Entering checkIPFSStatus"); boolean swarmConnectedStatus = false; try { MultiAddress multiAddress = new MultiAddress("/ipfs/" + peerid); - FunctionsLogger.info("MultiAdrress concated " + multiAddress + "|||"); + // FunctionsLogger.info("MultiAdrress concated " + multiAddress + "|||"); boolean output = swarmConnectP2P(peerid, ipfs); if (output) { swarmConnectedStatus = true; - FunctionsLogger.debug("Swarm is already connected"); + // FunctionsLogger.debug("Swarm is already connected"); } else { swarmConnectedStatus = false; - FunctionsLogger.debug("Swarm is not connected"); + // FunctionsLogger.debug("Swarm is not connected"); } } catch (Exception e) { - FunctionsLogger.error("Check Swarm Connect is failed", e); + FunctionsLogger.error("QuorumSendCredits Swarm Connect is failed", e); } - FunctionsLogger.info("checkIPFSStatus return value is " + swarmConnectedStatus); + // FunctionsLogger.info("checkIPFSStatus return value is " + + // swarmConnectedStatus); return swarmConnectedStatus; } - public static boolean ping(String peerid, int port) throws IOException, JSONException { + public static boolean ping(String peerid, int port) throws IOException { JSONObject pingCheck = PingCheck.Ping(peerid, port); - if (pingCheck.getString("status").contains("Failed")) { - return false; - } else - return true; + return !pingCheck.getString("status").contains("Failed"); + } + public static int arrangeQuorum(JSONArray quorumArray, int port, double amount) throws IOException { + pathSet(); + JSONArray quorumArrayRevised = new JSONArray(); + for (int i = 0; i < quorumArray.length(); i++) { + int credit = getCredits(quorumArray.getString(i), port); + // FunctionsLogger.debug("Credit received from " + quorumArray.getString(i) + " + // is: " + credit); + JSONObject peerCredit = new JSONObject(); + peerCredit.put("did", quorumArray.getString(i)); + peerCredit.put("credit", credit); + quorumArrayRevised.put(peerCredit); + } + if (quorumArrayRevised.length() < quorumArray.length()) { + FunctionsLogger.debug("Could not collect all credits"); + return 401; + } + + int i = 0; + JSONArray sortedQuorumArray = new JSONArray(); + while (quorumArrayRevised.length() > 0) { + JSONObject objectSelected = quorumArrayRevised.getJSONObject(i); + int creditSelected = quorumArrayRevised.getJSONObject(i).getInt("credit"); + + for (int j = i + 1; j < quorumArrayRevised.length(); j++) { + if (creditSelected < quorumArrayRevised.getJSONObject(j).getInt("credit")) { + objectSelected = quorumArrayRevised.getJSONObject(j); + creditSelected = quorumArrayRevised.getJSONObject(j).getInt("credit"); + } + } + sortedQuorumArray.put(objectSelected); + for (int j = 0; j < quorumArrayRevised.length(); j++) { + if (quorumArrayRevised.getJSONObject(j).getString("did").equals(objectSelected.getString("did"))) + quorumArrayRevised.remove(j); + } + } + + int totalAlpha = 0; + for (int j = 0; j < 7; j++) { + totalAlpha += sortedQuorumArray.getJSONObject(j).getInt("credit"); + } + FunctionsLogger.debug("7 alpha node credits sum up to: " + totalAlpha); + + if (totalAlpha < amount) { + FunctionsLogger.debug("7 alpha node credits not summing up to requested amount"); + return 402; + } + + JSONArray finalQuorumList = new JSONArray(); + for (int j = 0; j < sortedQuorumArray.length(); j++) + finalQuorumList.put(sortedQuorumArray.getJSONObject(j).getString("did")); + + writeToFile(DATA_PATH + "quorumlist.json", finalQuorumList.toString(), false); + + return 200; + } + + public static int getCredits(String peerid, int port) throws IOException { + JSONObject creditObject = GetCredits.Contact(peerid, port); + int credit = 0; + if (creditObject.getString("status").contains("Success")) + credit = creditObject.getInt("message"); + + return credit; } // public static String getPing(int port) { @@ -1615,32 +1685,35 @@ public static boolean ping(String peerid, int port) throws IOException, JSONExce // } public static boolean bootstrapConnect(String peerid, IPFS ipfs) { - FunctionsLogger.info("bootstrapConnect- entering function"); + // FunctionsLogger.info("bootstrapConnect- entering function"); String bootNode; boolean bootstrapConnected = false; MultiAddress multiAddress = new MultiAddress("/ipfs/" + peerid); - FunctionsLogger.info("bootstrapConnect- multiaddress is " + multiAddress.toString()); + // FunctionsLogger.info("bootstrapConnect- multiaddress is " + + // multiAddress.toString()); String output = swarmConnectProcess(multiAddress); try { for (int i = 0; i < BOOTSTRAPS.length(); i++) { - FunctionsLogger.info("bootstrapConnect- Bootstrap length is " + BOOTSTRAPS.length()); + // FunctionsLogger.info("bootstrapConnect- Bootstrap length is " + + // BOOTSTRAPS.length()); if (!bootstrapConnected) { - FunctionsLogger.info("bootstrapConnect- Connecting to bootstrp " + i); + // FunctionsLogger.info("bootstrapConnect- Connecting to bootstrp " + i); bootNode = String.valueOf(BOOTSTRAPS.get(i)); bootNode = bootNode.substring(bootNode.length() - 46); - FunctionsLogger.info("bootstrapConnect- trying to connect with " + bootNode); + // FunctionsLogger.info("bootstrapConnect- trying to connect with " + bootNode); multiAddress = new MultiAddress("/ipfs/" + bootNode); output = swarmConnectProcess(multiAddress); - FunctionsLogger.info("bootstrapConnect- connection status to " + bootNode + " is " + output); + // FunctionsLogger.info("bootstrapConnect- connection status to " + bootNode + " + // is " + output); if (output.contains("success")) { - FunctionsLogger.info("bootstrapConnect- trying to swarm connect"); + // FunctionsLogger.info("bootstrapConnect- trying to swarm connect"); multiAddress = new MultiAddress("/ipfs/" + bootNode + "/p2p-circuit/ipfs/" + peerid); output = swarmConnectProcess(multiAddress); - FunctionsLogger.info("bootstrapConnect- Swarmconnect status is " + output); + // FunctionsLogger.info("bootstrapConnect- Swarmconnect status is " + output); if (!output.contains("success")) { IPFSNetworkLogger.debug("swarm attempt failed with " + peerid); } else { @@ -1655,27 +1728,24 @@ public static boolean bootstrapConnect(String peerid, IPFS ipfs) { } } catch (Exception e) { - FunctionsLogger.error("Error occured during IPFS Swarm connect with bootstrap", e); + FunctionsLogger.error("Error occurred during IPFS Swarm connect with bootstrap", e); } - if (bootstrapConnected) { - return true; - } else { - return false; - } + return bootstrapConnected; } public static boolean portCheckAndKill(int port) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); boolean portStatus = false; - + long pid = ProcessHandle.current().pid(); + FunctionsLogger.info("Current OS is " + getOsName()); + FunctionsLogger.info("Current pid for the process is " + pid); try { - if (getOsName() != "Windows") { + if (!getOsName().toLowerCase().contains("windows")) { portStatus = releasePorts(port); } else { - portStatusWindows(port); portStatus = portStatusWindows(port); } } catch (Exception e) { @@ -1690,7 +1760,7 @@ public static boolean portCheckAndKill(int port) { * already in use */ public static boolean releasePorts(int port) { - FunctionsLogger.info("releasePorts- "); + // FunctionsLogger.info("releasePorts- "); boolean releasedPort = false; String processStr; Process processId; @@ -1699,31 +1769,33 @@ public static boolean releasePorts(int port) { long currentPid = ProcessHandle.current().pid(); BufferedReader br = new BufferedReader( new InputStreamReader(processId.getInputStream())); - FunctionsLogger.info("releasePorts- process " + br.readLine() + " is occupied in " + port); + // FunctionsLogger.info("releasePorts- process " + br.readLine() + " is occupied + // in " + port); processId = Runtime.getRuntime().exec("pgrep ipfs"); BufferedReader ipfsPidBr = new BufferedReader(new InputStreamReader(processId.getInputStream())); processStr = br.readLine(); - FunctionsLogger.info("releasePorts- Process string is " + processStr); + // FunctionsLogger.info("releasePorts- Process string is " + processStr); if (processStr != null) { - FunctionsLogger.info("releasePorts- Processstr is not null"); + // FunctionsLogger.info("releasePorts- Processstr is not null"); if (String.valueOf(currentPid) != processStr && ipfsPidBr.readLine() != processStr) { - FunctionsLogger.info("releasePorts- jar is running on " + currentPid + " and IPFS is occupied in " - + ipfsPidBr.readLine()); - FunctionsLogger.debug("Port " + port + " is in using, killing PID " + processStr); + // FunctionsLogger.info("releasePorts- jar is running on " + currentPid + " and + // IPFS is occupied in " + ipfsPidBr.readLine()); + // FunctionsLogger.debug("Port " + port + " is in using, killing PID " + + // processStr); processId = Runtime.getRuntime().exec("kill -9 " + processStr); - FunctionsLogger.info("releasePorts- killing " + processStr); + // FunctionsLogger.info("releasePorts- killing " + processStr); } } releasedPort = true; - FunctionsLogger.info("releasePorts- status is " + releasedPort); + // FunctionsLogger.info("releasePorts- status is " + releasedPort); processId.waitFor(); - FunctionsLogger.info("releasePorts- Waitng for process"); + // FunctionsLogger.info("releasePorts- Waitng for process"); processId.destroy(); - FunctionsLogger.info("releasePorts- destorying process after waiting"); + // FunctionsLogger.info("releasePorts- destorying process after waiting"); } catch (Exception e) { - FunctionsLogger.error("Exception Occured at releasePort", e); + FunctionsLogger.error("Exception Occurred at releasePort", e); e.printStackTrace(); } return releasedPort; @@ -1732,35 +1804,50 @@ public static boolean releasePorts(int port) { public static boolean portStatusWindows(int port) { FunctionsLogger.info("Starting portStatusWindows"); boolean releasedPort = false; - String processStr; + String portProcessStr; Process p; + ArrayList pidTree = new ArrayList(); + ArrayList portPidTree = new ArrayList(); try { Runtime rt = Runtime.getRuntime(); - Process proc = rt.exec("cmd /c netstat -ano | findstr " + port); - FunctionsLogger.info("Checking port status"); - long currentPid = ProcessHandle.current().pid(); - BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); - processStr = stdInput.readLine(); - FunctionsLogger.info("Process id found for port is " + processStr + " current jar pid is " + currentPid); - if (processStr != null && String.valueOf(currentPid) != processStr) { - int index = processStr.lastIndexOf(" "); - String sc = processStr.substring(index, processStr.length()); - // System.out.println("Port "+port+" is locked by PID "+sc+". Kindly close this - // port and retry transcation"); - if (sc != String.valueOf(currentPid)) { - FunctionsLogger.debug("Port " + port + " is locked by PID " + sc); - } else { - FunctionsLogger.debug("Port " + port + " is locked by current jar with PID " + sc); + Process getJarPid = rt.exec("cmd /c netstat -ano | findstr 1898"); + BufferedReader getJarPidBR = new BufferedReader(new InputStreamReader(getJarPid.getInputStream())); + String getJarPidline; + while ((getJarPidline = getJarPidBR.readLine()) != null) { + String[] getJarPidTree = getJarPidline.split("\\s+"); + int temp = Integer.parseInt(getJarPidTree[getJarPidTree.length - 1]); + pidTree.add(temp); + } + + FunctionsLogger.info("PIDs occupied by Rubix.jar are " + pidTree); + + Set pidSet = new LinkedHashSet(pidTree); + FunctionsLogger.info("Pid occupied by port 1898 is pidSet" + pidSet); + Process getPortPid = rt.exec("cmd /c netstat -ano | findstr " + port); + BufferedReader getPortPidBr = new BufferedReader(new InputStreamReader(getPortPid.getInputStream())); + String getPortPidLine; + while ((getPortPidLine = getPortPidBr.readLine()) != null) { + String[] getPortPidTree = getPortPidLine.split("\\s+"); + int temp = Integer.parseInt(getPortPidTree[getPortPidTree.length - 1]); + portPidTree.add(temp); } + + Set pidToKill = new LinkedHashSet(portPidTree); + FunctionsLogger.info("Pid used by port " + port + "is " + pidToKill); + pidToKill.removeAll(pidSet); + pidToKill.remove(0); + FunctionsLogger.info("Pid using port " + port + " but not in 1898" + pidToKill); + if (pidToKill.size() > 0) { + System.out.println("Port " + port + " is occupied by PIDs" + pidToKill); } else { releasedPort = true; - FunctionsLogger.info("Port is unlocked"); } + } catch (Exception e) { FunctionsLogger.error("Exception occured at portStatusWindows", e); - e.printStackTrace(); } return releasedPort; + } } 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/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 9eec6f97..5d782b60 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -40,11 +40,12 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; +import java.net.URL; import java.util.ArrayList; import java.util.Iterator; -import java.util.Random; import javax.imageio.ImageIO; +import javax.net.ssl.HttpsURLConnection; import com.rubix.AuthenticateNode.Authenticate; import com.rubix.AuthenticateNode.PropImage; @@ -202,64 +203,152 @@ public static String receive() { Double amount = tokenObject.getDouble("amount"); JSONObject amountLedger = tokenObject.getJSONObject("amountLedger"); TokenReceiverLogger.debug("Amount Ledger: " + amountLedger); + + JSONArray allTokens = new JSONArray(); + for (int i = 0; i < wholeTokens.length(); i++) + allTokens.put(wholeTokens.getString(i)); + for (int i = 0; i < partTokens.length(); i++) + allTokens.put(partTokens.getString(i)); + int intPart = wholeTokens.length(); + JSONArray wholeTokenContent = new JSONArray(); + for (int i = 0; i < intPart; i++) { + String TokenContent = get(wholeTokens.getString(i), ipfs); + wholeTokenContent.put(TokenContent); + } + + JSONArray partTokenContent = new JSONArray(); + for (int i = 0; i < partTokens.length(); i++) { + String TokenContent = get(partTokens.getString(i), ipfs); + partTokenContent.put(TokenContent); + } + JSONArray allTokensContent = new JSONArray(); + for (int i = 0; i < wholeTokenContent.length(); i++) { + allTokensContent.put(wholeTokenContent.getString(i)); + } + for (int i = 0; i < partTokenContent.length(); i++) { + allTokensContent.put(partTokenContent.getString(i)); + } + + boolean tokenMinedStatus = true; + String tokenMinedStatusErrorMessage = ""; + if (!Functions.EXPLORER_IP.contains("127.0.0.1")) { + TokenReceiverLogger.debug("Contacting Explorer ..." + EXPLORER_IP); + for (int i = 0; i < allTokensContent.length(); i++) { + + String token = allTokensContent.getString(i); + String url = Functions.EXPLORER_IP + "/check-mined-status/" + token; + URL obj = new URL(url); + HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); + + // Setting basic post request + con.setRequestMethod("GET"); + 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"); + + int responseCode = con.getResponseCode(); + TokenReceiverLogger.debug("Response Code : " + responseCode); + if (responseCode != 200) { + tokenMinedStatusErrorMessage = "Token Integrity Failed"; + TokenReceiverLogger.debug("Token Integrity Failed"); + tokenMinedStatus = false; + break; + } + + TokenReceiverLogger.debug("Reading status"); + BufferedReader in = new BufferedReader( + new InputStreamReader(con.getInputStream())); + String responseOutput; + StringBuffer response = new StringBuffer(); + + while ((responseOutput = in.readLine()) != null) { + response.append(responseOutput); + } + in.close(); + JSONObject responseObject = new JSONObject(response.toString()); + System.out.println("Status for token " + token + ": " + responseObject.getBoolean("status")); + if (!responseObject.getBoolean("status")) { + tokenMinedStatusErrorMessage = responseObject.getString("message"); + tokenMinedStatus = false; + break; + } + } + } else { + tokenMinedStatusErrorMessage = "Could not contact explorer: Explorer IP (127.0.0.1)"; + tokenMinedStatus = false; + } + if (!tokenMinedStatus) { + TokenReceiverLogger.debug(tokenMinedStatusErrorMessage); + output.println("419"); + output.println(tokenMinedStatusErrorMessage); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", tokenMinedStatusErrorMessage); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } // Double decimalPart = formatAmount(amount - intPart); - // JSONArray doubleSpentToken = new JSONArray(); - // boolean tokenOwners = true; - // ArrayList ownersArray = new ArrayList(); - // ArrayList previousSender = new ArrayList(); - // JSONArray ownersReceived = new JSONArray(); - // for (int i = 0; i < wholeTokens.length(); ++i) { - // try { - // TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + - // " Please wait..."); - // ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); - // - // if (ownersArray.size() > 2) { - // - // for (int j = 0; j < previousSendersArray.length(); j++) { - // if - // (previousSendersArray.getJSONObject(j).getString("token").equals(wholeTokens.getString(i))) - // ownersReceived = - // previousSendersArray.getJSONObject(j).getJSONArray("sender"); - // } - // - // for (int j = 0; j < ownersReceived.length(); j++) { - // previousSender.add(ownersReceived.getString(j)); - // } - // TokenReceiverLogger.debug("Previous Owners: " + previousSender); - // - // for (int j = 0; j < ownersArray.size(); j++) { - // if (!previousSender.contains(ownersArray.get(j).toString())) - // tokenOwners = false; - // } - // } - // } catch (IOException e) { - // - // TokenReceiverLogger.debug("Ipfs dht find did not execute"); - // } - // } - // if (!tokenOwners) { - // JSONArray owners = new JSONArray(); - // for (int i = 0; i < ownersArray.size(); i++) - // owners.put(ownersArray.get(i).toString()); - // TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); - // TokenReceiverLogger.debug("Owners: " + owners); - // output.println("420"); - // output.println(doubleSpentToken.toString()); - // output.println(owners.toString()); - // APIResponse.put("did", senderDidIpfsHash); - // APIResponse.put("tid", "null"); - // APIResponse.put("status", "Failed"); - // APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + - // owners); - // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - // output.close(); - // input.close(); - // sk.close(); - // ss.close(); - // return APIResponse.toString(); - // } + JSONArray doubleSpentToken = new JSONArray(); + boolean tokenOwners = true; + ArrayList ownersArray = new ArrayList(); + ArrayList previousSender = new ArrayList(); + JSONArray ownersReceived = new JSONArray(); + for (int i = 0; i < wholeTokens.length(); ++i) { + try { + TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + " Please wait..."); + ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); + + if (ownersArray.size() > 2) { + + for (int j = 0; j < previousSendersArray.length(); j++) { + if (previousSendersArray.getJSONObject(j).getString("token") + .equals(wholeTokens.getString(i))) + ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); + } + + for (int j = 0; j < ownersReceived.length(); j++) { + previousSender.add(ownersReceived.getString(j)); + } + TokenReceiverLogger.debug("Previous Owners: " + previousSender); + + for (int j = 0; j < ownersArray.size(); j++) { + if (!previousSender.contains(ownersArray.get(j).toString())) + doubleSpentToken.put(wholeTokens.getString(i)); + tokenOwners = false; + } + } + } catch (IOException e) { + + TokenReceiverLogger.debug("Ipfs dht find did not execute"); + } + } + if (!tokenOwners) { + JSONArray owners = new JSONArray(); + for (int i = 0; i < ownersArray.size(); i++) + owners.put(ownersArray.get(i).toString()); + TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); + TokenReceiverLogger.debug("Owners: " + owners); + output.println("420"); + output.println(doubleSpentToken.toString()); + output.println(owners.toString()); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + owners); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } String senderToken = TokenDetails.toString(); String consensusID = calculateHash(senderToken, "SHA3-256"); writeToFile(LOGGER_PATH + "consensusID", consensusID, false); @@ -410,13 +499,13 @@ public static String receive() { String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); - TokenReceiverLogger.debug("Ownership Here Sender Calculation"); - TokenReceiverLogger.debug("tokens: " + tokens); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); + // TokenReceiverLogger.debug("Ownership Here Sender Calculation"); + // TokenReceiverLogger.debug("tokens: " + tokens); + // TokenReceiverLogger.debug("hashString: " + hashString); + // TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + // TokenReceiverLogger.debug("p1: " + positionsArray.getString(i)); + // TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + // TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); if (!owner.equals(ownerRecalculated)) { ownerCheck = false; @@ -763,7 +852,7 @@ public static String receive() { for (int i = 0; i < intPart; i++) { FileWriter fileWriter; fileWriter = new FileWriter(TOKENS_PATH + wholeTokens.getString(i)); - fileWriter.write(wholeTokenContent.get(i)); + fileWriter.write(wholeTokenContent.getString(i)); fileWriter.close(); add(TOKENS_PATH + wholeTokens.getString(i), ipfs); pin(wholeTokens.getString(i), ipfs); @@ -823,13 +912,13 @@ public static String receive() { String ownerIdentity = hashForPositions.concat(positions); String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); - TokenReceiverLogger.debug("Ownership Here"); - TokenReceiverLogger.debug("tokens: " + wholeTokens.getString(i)); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positions); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); + // TokenReceiverLogger.debug("Ownership Here"); + // TokenReceiverLogger.debug("tokens: " + wholeTokens.getString(i)); + // TokenReceiverLogger.debug("hashString: " + hashString); + // TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + // TokenReceiverLogger.debug("p1: " + positions); + // TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + // TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); ArrayList groupTokens = new ArrayList<>(); for (int k = 0; k < intPart; k++) { @@ -883,13 +972,13 @@ public static String receive() { String ownerIdentity = hashForPositions.concat(positions); String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); - TokenReceiverLogger.debug("Ownership Here"); - TokenReceiverLogger.debug("tokens: " + partTokens.getString(i)); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positions); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); + // TokenReceiverLogger.debug("Ownership Here"); + // TokenReceiverLogger.debug("tokens: " + partTokens.getString(i)); + // TokenReceiverLogger.debug("hashString: " + hashString); + // TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + // TokenReceiverLogger.debug("p1: " + positions); + // TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + // TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); JSONObject newPartObject = new JSONObject(); newPartObject.put("senderSign", senderSignature); @@ -1035,9 +1124,7 @@ public static String receive() { 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(); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index c32b7336..7f38f176 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -10,6 +10,7 @@ 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.arrangeQuorum; import static com.rubix.Resources.Functions.calculateHash; import static com.rubix.Resources.Functions.deleteFile; import static com.rubix.Resources.Functions.formatAmount; @@ -385,6 +386,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception ArrayList betaPeersList; ArrayList gammaPeersList; + int arrangeCode = 0; JSONArray quorumArray; switch (type) { case 1: { @@ -403,6 +405,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception case 2: { quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + arrangeCode = arrangeQuorum(quorumArray, port + 15, requestedAmount); break; } case 3: { @@ -418,6 +421,27 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } + if (arrangeCode == 401) { + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + String message = "Could not collect all(min. 21) credits"; + APIResponse.put("message", message); + TokenSenderLogger.warn(message); + return APIResponse; + } else if (arrangeCode == 402) { + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + String message = "7 alpha node credits not summing up to requested amount"; + APIResponse.put("message", message); + TokenSenderLogger.warn(message); + senderMutex = false; + return APIResponse; + } else if (arrangeCode == 200) { + quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + } + int alphaCheck = 0, betaCheck = 0, gammaCheck = 0; JSONArray sanityFailedQuorum = new JSONArray(); for (int i = 0; i < quorumArray.length(); i++) { @@ -443,6 +467,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String message = "Quorum: ".concat(sanityFailedQuorum.toString()).concat(" "); APIResponse.put("message", message.concat(sanityMessage)); TokenSenderLogger.warn("Quorum: ".concat(message.concat(sanityMessage))); + senderMutex = false; return APIResponse; } @@ -467,7 +492,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception endTime = System.currentTimeMillis(); totalTime = endTime - startTime; - eventLogger.debug("Quorum Check " + totalTime); + eventLogger.debug("Quorum check " + totalTime); if (alphaPeersList.size() < minQuorum(alphaSize) || betaPeersList.size() < 5 || gammaPeersList.size() < 5) { updateQuorum(quorumArray, null, false, type); @@ -648,6 +673,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } if (tokenAuth != null && (tokenAuth.startsWith("4"))) { switch (tokenAuth) { + case "419": + String tokenAuthErrorMessage = input.readLine(); + TokenSenderLogger.info(tokenAuthErrorMessage); + TokenSenderLogger.info("Kindly re-initiate transaction later or with another token"); + APIResponse.put("message", tokenAuthErrorMessage + " Kindly re-initiate transaction"); + break; case "420": String doubleSpent = input.readLine(); String owners = input.readLine(); @@ -674,8 +705,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception case "424": String invalidTokens = input.readLine(); JSONArray tokensArray = new JSONArray(invalidTokens); - TokenSenderLogger.info("Ownership Check Failed for " + tokensArray); - APIResponse.put("message", "Ownership Check Failed"); + TokenSenderLogger.info("Ownership check Failed for " + tokensArray); + APIResponse.put("message", "Ownership check Failed"); break; case "425": @@ -697,7 +728,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("status", "Failed"); return APIResponse; } - TokenSenderLogger.debug("Token Auth Code: " + tokenAuth); JSONObject dataObject = new JSONObject(); dataObject.put("tid", tid); From ee1adf0b75397cad2f282a2002636b9f7aa7424b Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 24 Mar 2022 12:26:37 +0530 Subject: [PATCH 040/179] token reciever check sort Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Ping/QuorumPingReceive.java | 11 ++- src/com/rubix/Resources/APIHandler.java | 41 ++++++---- src/com/rubix/Resources/Functions.java | 76 +++++++++---------- .../rubix/TokenTransfer/TokenReceiver.java | 14 ++-- 4 files changed, 81 insertions(+), 61 deletions(-) diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java index 6abdbda2..a9cb15a7 100644 --- a/src/com/rubix/Ping/QuorumPingReceive.java +++ b/src/com/rubix/Ping/QuorumPingReceive.java @@ -3,13 +3,16 @@ 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.getPeerID; import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.Functions.readFile; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; import java.io.BufferedReader; +import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; @@ -19,6 +22,7 @@ import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -83,11 +87,12 @@ public static String receive(int port) throws JSONException { APIResponse.put("message", "Pong Sent"); QuorumPingReceiverLogger.info("Pong Sent"); - }if(pingRequest != null && pingRequest.contains("Get-Credits")) { + } + if (pingRequest != null && pingRequest.contains("Get-Credits")) { String qstFile = WALLET_DATA_PATH.concat("QuorumSignedTransactions.json"); File quorumFile = new File(qstFile); int unspentCredits = 0; - if(quorumFile.exists()){ + if (quorumFile.exists()) { String qFile = readFile(qstFile); JSONArray qArray = new JSONArray(qFile); unspentCredits = qArray.length(); @@ -98,7 +103,7 @@ public static String receive(int port) throws JSONException { APIResponse.put("message", "Credits Sent"); QuorumPingReceiverLogger.info("Credits Sent " + unspentCredits); - }else{ + } else { APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong Failed"); QuorumPingReceiverLogger.info("Pong Failed"); diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index d1d929b1..c0156711 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -3,19 +3,26 @@ 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.PAYMENTS_PATH; 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.WALLET_DATA_PATH; +import static com.rubix.Resources.Functions.arrangeQuorum; +import static com.rubix.Resources.Functions.calculateHash; 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.pathSet; import static com.rubix.Resources.Functions.readFile; +import static com.rubix.Resources.Functions.strToIntArray; 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.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -32,6 +39,9 @@ import java.util.Iterator; import java.util.List; +import javax.imageio.ImageIO; + +import com.rubix.AuthenticateNode.PropImage; import com.rubix.Mining.ProofCredits; import com.rubix.TokenTransfer.TokenSender; @@ -59,7 +69,7 @@ public class APIHandler { * @throws IOException handles IO Exceptions */ - public static JSONObject sortType2Quorum() { + public static JSONObject sortType2Quorum() throws JSONException { Functions.pathSet(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); JSONObject sendMessage = new JSONObject(); @@ -90,6 +100,7 @@ public static JSONObject sortType2Quorum() { return sendMessage; } + public static JSONObject send(String data) throws Exception { Functions.pathSet(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -167,8 +178,10 @@ public static JSONObject create(int type) throws Exception { /** * Utility function to add token ownership + * + * @throws JSONException */ - public static JSONObject addOwnership() throws IOException { + public static JSONObject addOwnership() throws IOException, JSONException { pathSet(); String wholeToken = readFile(PAYMENTS_PATH.concat("BNK00.json")); JSONArray wholeTokensArray = new JSONArray(wholeToken); @@ -298,19 +311,19 @@ public static JSONObject creditsInfo() throws JSONException { int spentCredits = 0; int unspentCredits = 0; try { - if (quorumFile.exists()) { - String qFile = readFile(qstFile); - JSONArray qArray = new JSONArray(qFile); - unspentCredits = qArray.length(); - } - if (minedFile.exists()) { - String mFile = readFile(mineFile); - JSONArray mArray = new JSONArray(mFile); - spentCredits = mArray.length(); - } + if (quorumFile.exists()) { + String qFile = readFile(qstFile); + JSONArray qArray = new JSONArray(qFile); + unspentCredits = qArray.length(); + } + if (minedFile.exists()) { + String mFile = readFile(mineFile); + JSONArray mArray = new JSONArray(mFile); + spentCredits = mArray.length(); + } - returnObject.put("spentCredits", spentCredits); - returnObject.put("unspentCredits", unspentCredits); + returnObject.put("spentCredits", spentCredits); + returnObject.put("unspentCredits", unspentCredits); } catch (JSONException e) { // TODO: handle exception } diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index f38f978c..c056ce5b 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1185,38 +1185,38 @@ public static void tokenBank() throws JSONException { pathSet(); String bank = readFile(PAYMENTS_PATH.concat("BNK00.json")); try { - JSONArray bankArray = new JSONArray(bank); + JSONArray bankArray = new JSONArray(bank); - ArrayList bankDuplicates = new ArrayList<>(); - for (int i = 0; i < bankArray.length(); i++) { - if (!bankDuplicates.contains(bankArray.getJSONObject(i).getString("tokenHash"))) - bankDuplicates.add(bankArray.getJSONObject(i).getString("tokenHash")); - } + ArrayList bankDuplicates = new ArrayList<>(); + for (int i = 0; i < bankArray.length(); i++) { + if (!bankDuplicates.contains(bankArray.getJSONObject(i).getString("tokenHash"))) + bankDuplicates.add(bankArray.getJSONObject(i).getString("tokenHash")); + } - if (bankDuplicates.size() < bankArray.length()) { - FunctionsLogger.debug("Duplicates Found. Cleaning up ..."); + if (bankDuplicates.size() < bankArray.length()) { + FunctionsLogger.debug("Duplicates Found. Cleaning up ..."); - JSONArray newBank = new JSONArray(); - for (int i = 0; i < bankDuplicates.size(); i++) { - JSONObject tokenObject = new JSONObject(); - tokenObject.put("tokenHash", bankDuplicates.get(i)); - newBank.put(tokenObject); + JSONArray newBank = new JSONArray(); + for (int i = 0; i < bankDuplicates.size(); i++) { + JSONObject tokenObject = new JSONObject(); + tokenObject.put("tokenHash", bankDuplicates.get(i)); + newBank.put(tokenObject); + } + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), newBank.toString(), false); } - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), newBank.toString(), false); - } - File tokensPath = new File(TOKENS_PATH); + File tokensPath = new File(TOKENS_PATH); String[] contents = tokensPath.list(); - ArrayList tokenFiles = new ArrayList(); - for (int i = 0; i < contents.length; i++) { - if (!contents[i].contains("PARTS")) - tokenFiles.add(contents[i]); - } + ArrayList tokenFiles = new ArrayList(); + for (int i = 0; i < contents.length; i++) { + if (!contents[i].contains("PARTS")) + tokenFiles.add(contents[i]); + } - for (int i = 0; i < tokenFiles.size(); i++) { - if (!bankDuplicates.contains(tokenFiles.get(i).toString())) - deleteFile(TOKENS_PATH.concat(tokenFiles.get(i).toString())); - } + for (int i = 0; i < tokenFiles.size(); i++) { + if (!bankDuplicates.contains(tokenFiles.get(i).toString())) + deleteFile(TOKENS_PATH.concat(tokenFiles.get(i).toString())); + } } catch (JSONException e) { // TODO: handle exception } @@ -1458,15 +1458,15 @@ public static Double formatAmount(Double amount) { public static void clearParts() throws JSONException { String partsFile = readFile(PAYMENTS_PATH.concat("PartsToken.json")); try { - JSONArray partsArray = new JSONArray(partsFile); - for (int i = 0; i < partsArray.length(); i++) { - if (partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) <= 0.000 - || partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) > 1.000) { - deleteFile(TOKENS_PATH.concat("PARTS/").concat(partsArray.getJSONObject(i).getString("tokenHash"))); - partsArray.remove(i); + JSONArray partsArray = new JSONArray(partsFile); + for (int i = 0; i < partsArray.length(); i++) { + if (partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) <= 0.000 + || partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) > 1.000) { + deleteFile(TOKENS_PATH.concat("PARTS/").concat(partsArray.getJSONObject(i).getString("tokenHash"))); + partsArray.remove(i); + } } - } - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partsArray.toString(), false); + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partsArray.toString(), false); } catch (JSONException e) { // TODO: handle exception } @@ -1494,7 +1494,7 @@ public static void backgroundChecks() { public static String sanityMessage; - public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOException { + public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOException, JSONException { // FunctionsLogger.info("Entering SanityCheck"); boolean sanityCheckErrorFlag = true; if (sanityCheckErrorFlag && checkIPFSStatus(peerid, ipfs)) { @@ -1569,12 +1569,12 @@ public static boolean checkIPFSStatus(String peerid, IPFS ipfs) { return swarmConnectedStatus; } - public static boolean ping(String peerid, int port) throws IOException { + public static boolean ping(String peerid, int port) throws IOException, JSONException { JSONObject pingCheck = PingCheck.Ping(peerid, port); return !pingCheck.getString("status").contains("Failed"); } - public static int arrangeQuorum(JSONArray quorumArray, int port, double amount) throws IOException { + public static int arrangeQuorum(JSONArray quorumArray, int port, double amount) throws IOException, JSONException { pathSet(); JSONArray quorumArrayRevised = new JSONArray(); for (int i = 0; i < quorumArray.length(); i++) { @@ -1630,7 +1630,7 @@ public static int arrangeQuorum(JSONArray quorumArray, int port, double amount) return 200; } - public static int getCredits(String peerid, int port) throws IOException { + public static int getCredits(String peerid, int port) throws IOException, JSONException { JSONObject creditObject = GetCredits.Contact(peerid, port); int credit = 0; if (creditObject.getString("status").contains("Success")) @@ -1830,7 +1830,7 @@ public static boolean portStatusWindows(int port) { String[] getPortPidTree = getPortPidLine.split("\\s+"); int temp = Integer.parseInt(getPortPidTree[getPortPidTree.length - 1]); portPidTree.add(temp); - } + } Set pidToKill = new LinkedHashSet(portPidTree); FunctionsLogger.info("Pid used by port " + port + "is " + pidToKill); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 5d782b60..ae5f710a 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -1,6 +1,7 @@ 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.FunctionsLogger; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; @@ -15,6 +16,7 @@ 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.intArrayToStr; import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.Functions.pathSet; import static com.rubix.Resources.Functions.readFile; @@ -43,13 +45,13 @@ import java.net.URL; import java.util.ArrayList; import java.util.Iterator; +import java.util.Random; import javax.imageio.ImageIO; import javax.net.ssl.HttpsURLConnection; import com.rubix.AuthenticateNode.Authenticate; import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; import org.apache.log4j.Logger; @@ -232,12 +234,12 @@ public static String receive() { boolean tokenMinedStatus = true; String tokenMinedStatusErrorMessage = ""; - if (!Functions.EXPLORER_IP.contains("127.0.0.1")) { + if (!EXPLORER_IP.contains("127.0.0.1")) { TokenReceiverLogger.debug("Contacting Explorer ..." + EXPLORER_IP); for (int i = 0; i < allTokensContent.length(); i++) { String token = allTokensContent.getString(i); - String url = Functions.EXPLORER_IP + "/check-mined-status/" + token; + String url = EXPLORER_IP + "/check-mined-status/" + token; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); @@ -904,7 +906,7 @@ public static String receive() { .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); String firstPrivate = PropImage.img2bin(pvt); int[] privateIntegerArray1 = strToIntArray(firstPrivate); - String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String privateBinary = intArrayToStr(privateIntegerArray1); String positions = ""; for (int j = 0; j < privateIntegerArray1.length; j += 49152) { positions += privateBinary.charAt(j); @@ -963,7 +965,7 @@ public static String receive() { .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); String firstPrivate = PropImage.img2bin(pvt); int[] privateIntegerArray1 = strToIntArray(firstPrivate); - String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String privateBinary = intArrayToStr(privateIntegerArray1); String positions = ""; for (int j = 0; j < privateIntegerArray1.length; j += 49152) { positions += privateBinary.charAt(j); @@ -1045,7 +1047,7 @@ public static String receive() { JSONObject tokenObject1 = new JSONObject(); tokenObject1.put("tokenHash", wholeTokens.getString(i)); bankArray.put(tokenObject1); - Functions.writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); } From 01159dfa4052c60afb70a17bfc1fecf83cb167e5 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 25 Mar 2022 00:04:18 +0530 Subject: [PATCH 041/179] revert token auth check Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Ping/GetCredits.java | 79 ----- src/com/rubix/Ping/PingReceive.java | 2 - src/com/rubix/Ping/QuorumPingReceive.java | 22 -- src/com/rubix/Resources/APIHandler.java | 139 +------- src/com/rubix/Resources/FractionChooser.java | 88 ----- src/com/rubix/Resources/Functions.java | 305 +++++++----------- src/com/rubix/Resources/IntegrityCheck.java | 22 +- .../rubix/TokenTransfer/TokenReceiver.java | 259 +++++---------- src/com/rubix/TokenTransfer/TokenSender.java | 38 +-- 9 files changed, 224 insertions(+), 730 deletions(-) delete mode 100644 src/com/rubix/Ping/GetCredits.java delete mode 100644 src/com/rubix/Resources/FractionChooser.java diff --git a/src/com/rubix/Ping/GetCredits.java b/src/com/rubix/Ping/GetCredits.java deleted file mode 100644 index 018feeea..00000000 --- a/src/com/rubix/Ping/GetCredits.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.rubix.Ping; - -import io.ipfs.api.IPFS; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.net.Socket; -import java.net.SocketException; - -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.*; - -public class GetCredits { - private static final Logger PingSenderLogger = Logger.getLogger(GetCredits.class); - public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); - - public static JSONObject Contact(String did, int port) throws IOException, JSONException { - repo(ipfs); - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - - String peerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", did); - - JSONObject APIResponse = new JSONObject(); - - String appName = peerID.concat("Ping"); - forward(appName, port, peerID); - PingSenderLogger.debug("Forwarded to " + appName + " on " + port + " for collecting credits"); - Socket senderSocket = new Socket("127.0.0.1", port); - - BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); - PrintStream output = new PrintStream(senderSocket.getOutputStream()); - - output.println("Get-Credits"); -// PingSenderLogger.debug("Sent Credits request"); - - String pongResponse; - try { - pongResponse = input.readLine(); - } catch (SocketException e) { - PingSenderLogger.warn("Quorum " + did + " is unable to Respond! - Credits Ping"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); - output.close(); - input.close(); - senderSocket.close(); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Quorum " + did + "is unable to respond! - Credits Ping"); - - return APIResponse; - } - - - if (pongResponse == null) { - executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); -// PingSenderLogger.info("Credits response not received"); - output.close(); - input.close(); - senderSocket.close(); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Credits response not received"); - - }else { - PingSenderLogger.info("Credits received from " + did); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); - output.close(); - input.close(); - senderSocket.close(); - APIResponse.put("status", "Success"); - APIResponse.put("message", Integer.parseInt(pongResponse)); - - } - return APIResponse; - } -} diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index 637dc3b0..de4a0cf0 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -96,8 +96,6 @@ public static String receive(int port) throws JSONException { } catch (IOException e) { e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); } return APIResponse.toString(); } diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java index a9cb15a7..354315df 100644 --- a/src/com/rubix/Ping/QuorumPingReceive.java +++ b/src/com/rubix/Ping/QuorumPingReceive.java @@ -3,16 +3,13 @@ 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.getPeerID; import static com.rubix.Resources.Functions.pathSet; -import static com.rubix.Resources.Functions.readFile; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; @@ -22,7 +19,6 @@ import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; -import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -87,22 +83,6 @@ public static String receive(int port) throws JSONException { APIResponse.put("message", "Pong Sent"); QuorumPingReceiverLogger.info("Pong Sent"); - } - if (pingRequest != null && pingRequest.contains("Get-Credits")) { - String qstFile = WALLET_DATA_PATH.concat("QuorumSignedTransactions.json"); - File quorumFile = new File(qstFile); - int unspentCredits = 0; - if (quorumFile.exists()) { - String qFile = readFile(qstFile); - JSONArray qArray = new JSONArray(qFile); - unspentCredits = qArray.length(); - } - output.println(unspentCredits); - - APIResponse.put("status", "Success"); - APIResponse.put("message", "Credits Sent"); - QuorumPingReceiverLogger.info("Credits Sent " + unspentCredits); - } else { APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong Failed"); @@ -116,8 +96,6 @@ public static String receive(int port) throws JSONException { } catch (IOException e) { e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); } return APIResponse.toString(); } diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index c0156711..466442dc 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -3,26 +3,19 @@ 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.PAYMENTS_PATH; 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.WALLET_DATA_PATH; -import static com.rubix.Resources.Functions.arrangeQuorum; -import static com.rubix.Resources.Functions.calculateHash; 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.pathSet; import static com.rubix.Resources.Functions.readFile; -import static com.rubix.Resources.Functions.strToIntArray; 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.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -39,9 +32,6 @@ import java.util.Iterator; import java.util.List; -import javax.imageio.ImageIO; - -import com.rubix.AuthenticateNode.PropImage; import com.rubix.Mining.ProofCredits; import com.rubix.TokenTransfer.TokenSender; @@ -69,38 +59,6 @@ public class APIHandler { * @throws IOException handles IO Exceptions */ - public static JSONObject sortType2Quorum() throws JSONException { - Functions.pathSet(); - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - JSONObject sendMessage = new JSONObject(); - JSONArray quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); - APILogger.debug("Before Sorting: " + quorumArray); - int code = 0; - try { - code = arrangeQuorum(quorumArray, SEND_PORT + 11, 0); - } catch (IOException e) { - APILogger.debug("Credits failed"); - } - - if (code == 200) { - quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); - APILogger.debug("After Sorting: " + quorumArray); - sendMessage.put("status", "Success"); - sendMessage.put("message", "Sorted"); - } else if (code == 401) { - APILogger.debug("Could not collect all(min. 21) credits"); - sendMessage.put("status", "Failed"); - sendMessage.put("message", ""); - } else if (code == 402) { - APILogger.debug("7 alpha node credits not summing up to requested amount"); - sendMessage.put("status", "Failed"); - sendMessage.put("message", ""); - } - - return sendMessage; - - } - public static JSONObject send(String data) throws Exception { Functions.pathSet(); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -176,72 +134,6 @@ public static JSONObject create(int type) throws Exception { return sendMessage; } - /** - * Utility function to add token ownership - * - * @throws JSONException - */ - public static JSONObject addOwnership() throws IOException, JSONException { - pathSet(); - String wholeToken = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray wholeTokensArray = new JSONArray(wholeToken); - String partsToken; - JSONArray partsTokenArray = new JSONArray(); - boolean parts = false; - if (new File(PAYMENTS_PATH.concat("PartsToken.json")).exists()) { - partsToken = readFile(PAYMENTS_PATH.concat("PartsToken.json")); - partsTokenArray = new JSONArray(partsToken); - parts = true; - } - JSONArray allTokens = new JSONArray(); - for (int i = 0; i < wholeTokensArray.length(); i++) - allTokens.put(wholeTokensArray.getString(i)); - - if (parts) { - for (int i = 0; i < partsTokenArray.length(); i++) - allTokens.put(partsTokenArray.getString(i)); - } - - String didFile = readFile(DATA_PATH.concat("DID.json")); - JSONArray didArray = new JSONArray(didFile); - String did = didArray.getJSONObject(0).getString("didHash"); - - for (int i = 0; i < allTokens.length(); i++) { - String tokens = allTokens.getString(i); - String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokens).concat(".json")); - JSONArray tokenChainArray = new JSONArray(tokenChain); - JSONObject lastObject = tokenChainArray.getJSONObject(tokenChainArray.length() - 1); - if (!lastObject.has("owner")) { - String hashString = tokens.concat(did); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - - BufferedImage pvt = ImageIO.read(new File(DATA_PATH.concat(did).concat("/PrivateShare.png"))); - String firstPrivate = PropImage.img2bin(pvt); - int[] privateIntegerArray1 = strToIntArray(firstPrivate); - String privateBinary = Functions.intArrayToStr(privateIntegerArray1); - String positions = ""; - for (int j = 0; j < privateIntegerArray1.length; j += 49152) { - positions += privateBinary.charAt(j); - } - String ownerIdentity = hashForPositions.concat(positions); - String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); - lastObject.put("owner", ownerIdentityHash); - } - tokenChainArray.remove(tokenChainArray.length() - 1); - tokenChainArray.put(lastObject); - writeToFile(TOKENCHAIN_PATH.concat(tokens).concat(".json"), tokenChainArray.toString(), false); - - } - - JSONObject sendMessage = new JSONObject(); - sendMessage.put("did", did); - sendMessage.put("tid", "null"); - sendMessage.put("status", "Success"); - sendMessage.put("message", "Ownership Added"); - return sendMessage; - - } - /** * A method to add and host your DID ans Public share to ipfs * @@ -307,27 +199,24 @@ public static JSONObject creditsInfo() throws JSONException { File quorumFile = new File(qstFile); File minedFile = new File(mineFile); - JSONObject returnObject = new JSONObject(); + int spentCredits = 0; int unspentCredits = 0; - try { - if (quorumFile.exists()) { - String qFile = readFile(qstFile); - JSONArray qArray = new JSONArray(qFile); - unspentCredits = qArray.length(); - } - if (minedFile.exists()) { - String mFile = readFile(mineFile); - JSONArray mArray = new JSONArray(mFile); - spentCredits = mArray.length(); - } - - returnObject.put("spentCredits", spentCredits); - returnObject.put("unspentCredits", unspentCredits); - } catch (JSONException e) { - // TODO: handle exception + if (quorumFile.exists()) { + String qFile = readFile(qstFile); + JSONArray qArray = new JSONArray(qFile); + unspentCredits = qArray.length(); + } + if (minedFile.exists()) { + String mFile = readFile(mineFile); + JSONArray mArray = new JSONArray(mFile); + spentCredits = mArray.length(); } + JSONObject returnObject = new JSONObject(); + returnObject.put("spentCredits", spentCredits); + returnObject.put("unspentCredits", unspentCredits); + return returnObject; } diff --git a/src/com/rubix/Resources/FractionChooser.java b/src/com/rubix/Resources/FractionChooser.java deleted file mode 100644 index 4f328c6c..00000000 --- a/src/com/rubix/Resources/FractionChooser.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.rubix.Resources; - - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import org.apache.log4j.*; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import static com.rubix.Resources.Functions.*; - -public class FractionChooser { - public static String output; - - public static JSONArray tokenHeader; - - public static Logger FractionChooserLogger = Logger.getLogger(FractionChooser.class); - - public static JSONArray calculate(int amount) { - JSONArray tokensList = new JSONArray(); - tokenHeader = new JSONArray(); - JSONObject tknmap = new JSONObject(); - try { - int index = 0; - LinkedHashMap map = new LinkedHashMap<>(); - LinkedHashMap usedmap = new LinkedHashMap<>(); - List bnk = new ArrayList<>(); - if (amount < 1) { - FractionChooserLogger.warn("Invalid Transaction Amount"); - output = "Please make a valid transaction"; - return tokensList; - } - JSONArray mapList = new JSONArray(readFile(PAYMENTS_PATH + "TokenMap.json")); - int i; - for (i = 0; i < mapList.length(); i++) { - JSONObject tempJsonObject = mapList.getJSONObject(i); - String type = tempJsonObject.getString("type"); - int valueInt = tempJsonObject.getInt("value"); - tknmap.put(String.valueOf(valueInt), type); - String lists = readFile(PAYMENTS_PATH + tempJsonObject.getString("type") + ".json"); - JSONArray tempJsonArray = new JSONArray(lists); - bnk.add(i, tempJsonArray); - int size = tempJsonArray.length(); - map.put(Integer.valueOf(valueInt), Integer.valueOf(size)); - usedmap.put(Integer.valueOf(valueInt), Integer.valueOf(0)); - } - List keyList = new ArrayList(map.keySet()); - for (i = map.size() - 1; i > 0; i--) { - if (((Integer)keyList.get(i)).intValue() <= amount) { - index = i; - break; - } - } - while (amount != 0) { - int valueInt = ((Integer)keyList.get(index)).intValue(); - if (((Integer)map.get(Integer.valueOf(valueInt))).intValue() > 0 && valueInt <= amount) { - amount -= valueInt; - int temp = ((Integer)usedmap.get(Integer.valueOf(valueInt))).intValue(); - int temp1 = ((Integer)map.get(Integer.valueOf(valueInt))).intValue(); - usedmap.put(Integer.valueOf(valueInt), Integer.valueOf(++temp)); - map.put(Integer.valueOf(valueInt), Integer.valueOf(--temp1)); - } else if (index != 0) { - index--; - } else { - FractionChooserLogger.warn("Insufficient Amount in the Wallet. Required " + amount + " currency"); - output = "Balance not sufficient, need " + amount + " more currency"; - return tokensList; - } - if (valueInt > amount && index != 0) - index--; - } - for (i = 0; i < keyList.size(); i++) { - for (int j = 0; j < ((Integer)usedmap.get(keyList.get(i))).intValue(); j++) { - tokensList.put(((JSONArray)bnk.get(i)).getJSONObject(j).getString("tokenHash")); - tokenHeader.put(tknmap.get(String.valueOf(keyList.get(i)))); - } - } - } catch (JSONException e) { - FractionChooserLogger.error("JSON Exception Occurred", (Throwable)e); - e.printStackTrace(); - } - FractionChooserLogger.debug("Tokens chosen to be sent: " + tokensList); - return tokensList; - } -} - diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index c056ce5b..7a702ac6 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -32,13 +32,10 @@ import java.util.ArrayList; import java.util.Date; import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Set; import javax.imageio.ImageIO; import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Ping.GetCredits; import com.rubix.Ping.PingCheck; import org.apache.log4j.Logger; @@ -921,7 +918,7 @@ public static String mineToken(int level, int tokenNumber) { String levelHex = Integer.toHexString(level); if (level < 16) levelHex = String.valueOf(0).concat(levelHex); - String token = 0 + levelHex + tokenHash; + String token = String.valueOf(0) + levelHex + tokenHash; return token; } @@ -943,7 +940,10 @@ public static String toBinary(int x, int len) { public static Boolean integrityCheck(String consensusID) { File file = new File(WALLET_DATA_PATH + "QuorumSignedTransactions.json"); if (file.exists()) { - return getValues(file.getAbsolutePath(), "senderdid", "consensusID", consensusID).equals(""); + if (getValues(file.getAbsolutePath(), "senderdid", "consensusID", consensusID).equals("")) + return true; + else + return false; } else return true; } @@ -1184,41 +1184,37 @@ public static void correctPartToken() throws JSONException { public static void tokenBank() throws JSONException { pathSet(); String bank = readFile(PAYMENTS_PATH.concat("BNK00.json")); - try { - JSONArray bankArray = new JSONArray(bank); + JSONArray bankArray = new JSONArray(bank); - ArrayList bankDuplicates = new ArrayList<>(); - for (int i = 0; i < bankArray.length(); i++) { - if (!bankDuplicates.contains(bankArray.getJSONObject(i).getString("tokenHash"))) - bankDuplicates.add(bankArray.getJSONObject(i).getString("tokenHash")); - } + ArrayList bankDuplicates = new ArrayList<>(); + for (int i = 0; i < bankArray.length(); i++) { + if (!bankDuplicates.contains(bankArray.getJSONObject(i).getString("tokenHash"))) + bankDuplicates.add(bankArray.getJSONObject(i).getString("tokenHash")); + } - if (bankDuplicates.size() < bankArray.length()) { - FunctionsLogger.debug("Duplicates Found. Cleaning up ..."); + if (bankDuplicates.size() < bankArray.length()) { + FunctionsLogger.debug("Duplicates Found. Cleaning up ..."); - JSONArray newBank = new JSONArray(); - for (int i = 0; i < bankDuplicates.size(); i++) { - JSONObject tokenObject = new JSONObject(); - tokenObject.put("tokenHash", bankDuplicates.get(i)); - newBank.put(tokenObject); - } - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), newBank.toString(), false); + JSONArray newBank = new JSONArray(); + for (int i = 0; i < bankDuplicates.size(); i++) { + JSONObject tokenObject = new JSONObject(); + tokenObject.put("tokenHash", bankDuplicates.get(i)); + newBank.put(tokenObject); } + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), newBank.toString(), false); + } - File tokensPath = new File(TOKENS_PATH); - String[] contents = tokensPath.list(); - ArrayList tokenFiles = new ArrayList(); - for (int i = 0; i < contents.length; i++) { - if (!contents[i].contains("PARTS")) - tokenFiles.add(contents[i]); - } + File tokensPath = new File(TOKENS_PATH); + String contents[] = tokensPath.list(); + ArrayList tokenFiles = new ArrayList(); + for (int i = 0; i < contents.length; i++) { + if (!contents[i].contains("PARTS")) + tokenFiles.add(contents[i]); + } - for (int i = 0; i < tokenFiles.size(); i++) { - if (!bankDuplicates.contains(tokenFiles.get(i).toString())) - deleteFile(TOKENS_PATH.concat(tokenFiles.get(i).toString())); - } - } catch (JSONException e) { - // TODO: handle exception + for (int i = 0; i < tokenFiles.size(); i++) { + if (!bankDuplicates.contains(tokenFiles.get(i).toString())) + deleteFile(TOKENS_PATH.concat(tokenFiles.get(i).toString())); } } @@ -1457,19 +1453,15 @@ public static Double formatAmount(Double amount) { public static void clearParts() throws JSONException { String partsFile = readFile(PAYMENTS_PATH.concat("PartsToken.json")); - try { - JSONArray partsArray = new JSONArray(partsFile); - for (int i = 0; i < partsArray.length(); i++) { - if (partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) <= 0.000 - || partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) > 1.000) { - deleteFile(TOKENS_PATH.concat("PARTS/").concat(partsArray.getJSONObject(i).getString("tokenHash"))); - partsArray.remove(i); - } + JSONArray partsArray = new JSONArray(partsFile); + for (int i = 0; i < partsArray.length(); i++) { + if (partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) <= 0.000 + || partTokenBalance(partsArray.getJSONObject(i).getString("tokenHash")) > 1.000) { + deleteFile(TOKENS_PATH.concat("PARTS/").concat(partsArray.getJSONObject(i).getString("tokenHash"))); + partsArray.remove(i); } - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partsArray.toString(), false); - } catch (JSONException e) { - // TODO: handle exception } + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partsArray.toString(), false); } public static void backgroundChecks() { @@ -1495,26 +1487,26 @@ public static void backgroundChecks() { public static String sanityMessage; public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOException, JSONException { - // FunctionsLogger.info("Entering SanityCheck"); + FunctionsLogger.info("Entering SanityCheck"); boolean sanityCheckErrorFlag = true; if (sanityCheckErrorFlag && checkIPFSStatus(peerid, ipfs)) { FunctionsLogger.debug("IPFS is working in " + peerid); - // FunctionsLogger.debug("IPFS check true"); + FunctionsLogger.debug("IPFS check true"); } else { sanityCheckErrorFlag = false; - // FunctionsLogger.debug("IPFS is not working in " + peerid); - // FunctionsLogger.debug("IPFS check false"); + FunctionsLogger.debug("IPFS is not working in " + peerid); + FunctionsLogger.debug("IPFS check false"); sanityMessage = "IPFS is not working in " + peerid; } if (sanityCheckErrorFlag) { if (bootstrapConnect(peerid, ipfs)) { FunctionsLogger.debug("Bootstrap connected for " + peerid); - // FunctionsLogger.debug("Bootstrap check true"); + FunctionsLogger.debug("Bootstrap check true"); } else { sanityCheckErrorFlag = false; - // FunctionsLogger.debug("Bootstrap connection unsuccessful for " + peerid); - // FunctionsLogger.debug("Bootstrap check false"); + FunctionsLogger.debug("Bootstrap connection unsuccessful for " + peerid); + FunctionsLogger.debug("Bootstrap check false"); sanityMessage = "Bootstrap connection unsuccessful for " + peerid; } } @@ -1522,22 +1514,22 @@ public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOE if (sanityCheckErrorFlag) { if (ping(peerid, port)) { FunctionsLogger.debug("Jar is running as expected in " + peerid); - // FunctionsLogger.debug("Jar check true"); + FunctionsLogger.debug("Jar check true"); } else { sanityCheckErrorFlag = false; - // FunctionsLogger.debug("Jar is not running in " + peerid); - // FunctionsLogger.debug("Jar check false"); + FunctionsLogger.debug("Jar is not running in " + peerid); + FunctionsLogger.debug("Jar check false"); sanityMessage = "Jar is not running in " + peerid; } } if (sanityCheckErrorFlag) { if (portCheckAndKill(port)) { - FunctionsLogger.debug("Ports are available for transactions in " + peerid); - // FunctionsLogger.debug("Ports check true"); + FunctionsLogger.debug("Ports are available for transcations in " + peerid); + FunctionsLogger.debug("Ports check true"); } else { sanityCheckErrorFlag = false; - // FunctionsLogger.debug("Ports are not available for " + peerid); - // FunctionsLogger.debug("Ports check false"); + FunctionsLogger.debug("Ports are not available for " + peerid); + FunctionsLogger.debug("Ports check false"); sanityMessage = "Ports are not available for " + peerid; } } @@ -1546,97 +1538,35 @@ public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOE } public static boolean checkIPFSStatus(String peerid, IPFS ipfs) { - // FunctionsLogger.info("Entering checkIPFSStatus"); + FunctionsLogger.info("Entering checkIPFSStatus"); boolean swarmConnectedStatus = false; try { MultiAddress multiAddress = new MultiAddress("/ipfs/" + peerid); - // FunctionsLogger.info("MultiAdrress concated " + multiAddress + "|||"); + FunctionsLogger.info("MultiAdrress concated " + multiAddress + "|||"); boolean output = swarmConnectP2P(peerid, ipfs); if (output) { swarmConnectedStatus = true; - // FunctionsLogger.debug("Swarm is already connected"); + FunctionsLogger.debug("Swarm is already connected"); } else { swarmConnectedStatus = false; - // FunctionsLogger.debug("Swarm is not connected"); + FunctionsLogger.debug("Swarm is not connected"); } } catch (Exception e) { - FunctionsLogger.error("QuorumSendCredits Swarm Connect is failed", e); + FunctionsLogger.error("Check Swarm Connect is failed", e); } - // FunctionsLogger.info("checkIPFSStatus return value is " + - // swarmConnectedStatus); + FunctionsLogger.info("checkIPFSStatus return value is " + swarmConnectedStatus); return swarmConnectedStatus; } public static boolean ping(String peerid, int port) throws IOException, JSONException { JSONObject pingCheck = PingCheck.Ping(peerid, port); - return !pingCheck.getString("status").contains("Failed"); - } - - public static int arrangeQuorum(JSONArray quorumArray, int port, double amount) throws IOException, JSONException { - pathSet(); - JSONArray quorumArrayRevised = new JSONArray(); - for (int i = 0; i < quorumArray.length(); i++) { - int credit = getCredits(quorumArray.getString(i), port); - // FunctionsLogger.debug("Credit received from " + quorumArray.getString(i) + " - // is: " + credit); - JSONObject peerCredit = new JSONObject(); - peerCredit.put("did", quorumArray.getString(i)); - peerCredit.put("credit", credit); - quorumArrayRevised.put(peerCredit); - } - if (quorumArrayRevised.length() < quorumArray.length()) { - FunctionsLogger.debug("Could not collect all credits"); - return 401; - } - - int i = 0; - JSONArray sortedQuorumArray = new JSONArray(); - while (quorumArrayRevised.length() > 0) { - JSONObject objectSelected = quorumArrayRevised.getJSONObject(i); - int creditSelected = quorumArrayRevised.getJSONObject(i).getInt("credit"); - - for (int j = i + 1; j < quorumArrayRevised.length(); j++) { - if (creditSelected < quorumArrayRevised.getJSONObject(j).getInt("credit")) { - objectSelected = quorumArrayRevised.getJSONObject(j); - creditSelected = quorumArrayRevised.getJSONObject(j).getInt("credit"); - } - } - sortedQuorumArray.put(objectSelected); - for (int j = 0; j < quorumArrayRevised.length(); j++) { - if (quorumArrayRevised.getJSONObject(j).getString("did").equals(objectSelected.getString("did"))) - quorumArrayRevised.remove(j); - } - } - - int totalAlpha = 0; - for (int j = 0; j < 7; j++) { - totalAlpha += sortedQuorumArray.getJSONObject(j).getInt("credit"); - } - FunctionsLogger.debug("7 alpha node credits sum up to: " + totalAlpha); - - if (totalAlpha < amount) { - FunctionsLogger.debug("7 alpha node credits not summing up to requested amount"); - return 402; - } - - JSONArray finalQuorumList = new JSONArray(); - for (int j = 0; j < sortedQuorumArray.length(); j++) - finalQuorumList.put(sortedQuorumArray.getJSONObject(j).getString("did")); - - writeToFile(DATA_PATH + "quorumlist.json", finalQuorumList.toString(), false); - - return 200; - } - - public static int getCredits(String peerid, int port) throws IOException, JSONException { - JSONObject creditObject = GetCredits.Contact(peerid, port); - int credit = 0; - if (creditObject.getString("status").contains("Success")) - credit = creditObject.getInt("message"); + if (pingCheck.getString("status").contains("Failed")) { + return false; + } else + return true; - return credit; } // public static String getPing(int port) { @@ -1685,35 +1615,32 @@ public static int getCredits(String peerid, int port) throws IOException, JSONEx // } public static boolean bootstrapConnect(String peerid, IPFS ipfs) { - // FunctionsLogger.info("bootstrapConnect- entering function"); + FunctionsLogger.info("bootstrapConnect- entering function"); String bootNode; boolean bootstrapConnected = false; MultiAddress multiAddress = new MultiAddress("/ipfs/" + peerid); - // FunctionsLogger.info("bootstrapConnect- multiaddress is " + - // multiAddress.toString()); + FunctionsLogger.info("bootstrapConnect- multiaddress is " + multiAddress.toString()); String output = swarmConnectProcess(multiAddress); try { for (int i = 0; i < BOOTSTRAPS.length(); i++) { - // FunctionsLogger.info("bootstrapConnect- Bootstrap length is " + - // BOOTSTRAPS.length()); + FunctionsLogger.info("bootstrapConnect- Bootstrap length is " + BOOTSTRAPS.length()); if (!bootstrapConnected) { - // FunctionsLogger.info("bootstrapConnect- Connecting to bootstrp " + i); + FunctionsLogger.info("bootstrapConnect- Connecting to bootstrp " + i); bootNode = String.valueOf(BOOTSTRAPS.get(i)); bootNode = bootNode.substring(bootNode.length() - 46); - // FunctionsLogger.info("bootstrapConnect- trying to connect with " + bootNode); + FunctionsLogger.info("bootstrapConnect- trying to connect with " + bootNode); multiAddress = new MultiAddress("/ipfs/" + bootNode); output = swarmConnectProcess(multiAddress); - // FunctionsLogger.info("bootstrapConnect- connection status to " + bootNode + " - // is " + output); + FunctionsLogger.info("bootstrapConnect- connection status to " + bootNode + " is " + output); if (output.contains("success")) { - // FunctionsLogger.info("bootstrapConnect- trying to swarm connect"); + FunctionsLogger.info("bootstrapConnect- trying to swarm connect"); multiAddress = new MultiAddress("/ipfs/" + bootNode + "/p2p-circuit/ipfs/" + peerid); output = swarmConnectProcess(multiAddress); - // FunctionsLogger.info("bootstrapConnect- Swarmconnect status is " + output); + FunctionsLogger.info("bootstrapConnect- Swarmconnect status is " + output); if (!output.contains("success")) { IPFSNetworkLogger.debug("swarm attempt failed with " + peerid); } else { @@ -1728,24 +1655,27 @@ public static boolean bootstrapConnect(String peerid, IPFS ipfs) { } } catch (Exception e) { - FunctionsLogger.error("Error occurred during IPFS Swarm connect with bootstrap", e); + FunctionsLogger.error("Error occured during IPFS Swarm connect with bootstrap", e); } - return bootstrapConnected; + if (bootstrapConnected) { + return true; + } else { + return false; + } } public static boolean portCheckAndKill(int port) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); boolean portStatus = false; - long pid = ProcessHandle.current().pid(); - FunctionsLogger.info("Current OS is " + getOsName()); - FunctionsLogger.info("Current pid for the process is " + pid); + try { - if (!getOsName().toLowerCase().contains("windows")) { + if (getOsName() != "Windows") { portStatus = releasePorts(port); } else { + portStatusWindows(port); portStatus = portStatusWindows(port); } } catch (Exception e) { @@ -1760,7 +1690,7 @@ public static boolean portCheckAndKill(int port) { * already in use */ public static boolean releasePorts(int port) { - // FunctionsLogger.info("releasePorts- "); + FunctionsLogger.info("releasePorts- "); boolean releasedPort = false; String processStr; Process processId; @@ -1769,33 +1699,31 @@ public static boolean releasePorts(int port) { long currentPid = ProcessHandle.current().pid(); BufferedReader br = new BufferedReader( new InputStreamReader(processId.getInputStream())); - // FunctionsLogger.info("releasePorts- process " + br.readLine() + " is occupied - // in " + port); + FunctionsLogger.info("releasePorts- process " + br.readLine() + " is occupied in " + port); processId = Runtime.getRuntime().exec("pgrep ipfs"); BufferedReader ipfsPidBr = new BufferedReader(new InputStreamReader(processId.getInputStream())); processStr = br.readLine(); - // FunctionsLogger.info("releasePorts- Process string is " + processStr); + FunctionsLogger.info("releasePorts- Process string is " + processStr); if (processStr != null) { - // FunctionsLogger.info("releasePorts- Processstr is not null"); + FunctionsLogger.info("releasePorts- Processstr is not null"); if (String.valueOf(currentPid) != processStr && ipfsPidBr.readLine() != processStr) { - // FunctionsLogger.info("releasePorts- jar is running on " + currentPid + " and - // IPFS is occupied in " + ipfsPidBr.readLine()); - // FunctionsLogger.debug("Port " + port + " is in using, killing PID " + - // processStr); + FunctionsLogger.info("releasePorts- jar is running on " + currentPid + " and IPFS is occupied in " + + ipfsPidBr.readLine()); + FunctionsLogger.debug("Port " + port + " is in using, killing PID " + processStr); processId = Runtime.getRuntime().exec("kill -9 " + processStr); - // FunctionsLogger.info("releasePorts- killing " + processStr); + FunctionsLogger.info("releasePorts- killing " + processStr); } } releasedPort = true; - // FunctionsLogger.info("releasePorts- status is " + releasedPort); + FunctionsLogger.info("releasePorts- status is " + releasedPort); processId.waitFor(); - // FunctionsLogger.info("releasePorts- Waitng for process"); + FunctionsLogger.info("releasePorts- Waitng for process"); processId.destroy(); - // FunctionsLogger.info("releasePorts- destorying process after waiting"); + FunctionsLogger.info("releasePorts- destorying process after waiting"); } catch (Exception e) { - FunctionsLogger.error("Exception Occurred at releasePort", e); + FunctionsLogger.error("Exception Occured at releasePort", e); e.printStackTrace(); } return releasedPort; @@ -1804,50 +1732,35 @@ public static boolean releasePorts(int port) { public static boolean portStatusWindows(int port) { FunctionsLogger.info("Starting portStatusWindows"); boolean releasedPort = false; - String portProcessStr; + String processStr; Process p; - ArrayList pidTree = new ArrayList(); - ArrayList portPidTree = new ArrayList(); try { Runtime rt = Runtime.getRuntime(); - Process getJarPid = rt.exec("cmd /c netstat -ano | findstr 1898"); - BufferedReader getJarPidBR = new BufferedReader(new InputStreamReader(getJarPid.getInputStream())); - String getJarPidline; - while ((getJarPidline = getJarPidBR.readLine()) != null) { - String[] getJarPidTree = getJarPidline.split("\\s+"); - int temp = Integer.parseInt(getJarPidTree[getJarPidTree.length - 1]); - pidTree.add(temp); - } - - FunctionsLogger.info("PIDs occupied by Rubix.jar are " + pidTree); - - Set pidSet = new LinkedHashSet(pidTree); - FunctionsLogger.info("Pid occupied by port 1898 is pidSet" + pidSet); - Process getPortPid = rt.exec("cmd /c netstat -ano | findstr " + port); - BufferedReader getPortPidBr = new BufferedReader(new InputStreamReader(getPortPid.getInputStream())); - String getPortPidLine; - while ((getPortPidLine = getPortPidBr.readLine()) != null) { - String[] getPortPidTree = getPortPidLine.split("\\s+"); - int temp = Integer.parseInt(getPortPidTree[getPortPidTree.length - 1]); - portPidTree.add(temp); - } - - Set pidToKill = new LinkedHashSet(portPidTree); - FunctionsLogger.info("Pid used by port " + port + "is " + pidToKill); - pidToKill.removeAll(pidSet); - pidToKill.remove(0); - FunctionsLogger.info("Pid using port " + port + " but not in 1898" + pidToKill); - if (pidToKill.size() > 0) { - System.out.println("Port " + port + " is occupied by PIDs" + pidToKill); + Process proc = rt.exec("cmd /c netstat -ano | findstr " + port); + FunctionsLogger.info("Checking port status"); + long currentPid = ProcessHandle.current().pid(); + BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); + processStr = stdInput.readLine(); + FunctionsLogger.info("Process id found for port is " + processStr + " current jar pid is " + currentPid); + if (processStr != null && String.valueOf(currentPid) != processStr) { + int index = processStr.lastIndexOf(" "); + String sc = processStr.substring(index, processStr.length()); + // System.out.println("Port "+port+" is locked by PID "+sc+". Kindly close this + // port and retry transcation"); + if (sc != String.valueOf(currentPid)) { + FunctionsLogger.debug("Port " + port + " is locked by PID " + sc); + } else { + FunctionsLogger.debug("Port " + port + " is locked by current jar with PID " + sc); + } } else { releasedPort = true; + FunctionsLogger.info("Port is unlocked"); } - } catch (Exception e) { FunctionsLogger.error("Exception occured at portStatusWindows", e); + e.printStackTrace(); } return releasedPort; - } } diff --git a/src/com/rubix/Resources/IntegrityCheck.java b/src/com/rubix/Resources/IntegrityCheck.java index 33917e81..d83d8c1f 100644 --- a/src/com/rubix/Resources/IntegrityCheck.java +++ b/src/com/rubix/Resources/IntegrityCheck.java @@ -7,14 +7,16 @@ 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; } @@ -30,7 +32,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; } @@ -38,20 +40,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/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index ae5f710a..9eec6f97 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -1,7 +1,6 @@ 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.FunctionsLogger; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; @@ -16,7 +15,6 @@ 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.intArrayToStr; import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.Functions.pathSet; import static com.rubix.Resources.Functions.readFile; @@ -42,16 +40,15 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; -import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.Random; import javax.imageio.ImageIO; -import javax.net.ssl.HttpsURLConnection; import com.rubix.AuthenticateNode.Authenticate; import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; import org.apache.log4j.Logger; @@ -205,152 +202,64 @@ public static String receive() { Double amount = tokenObject.getDouble("amount"); JSONObject amountLedger = tokenObject.getJSONObject("amountLedger"); TokenReceiverLogger.debug("Amount Ledger: " + amountLedger); - - JSONArray allTokens = new JSONArray(); - for (int i = 0; i < wholeTokens.length(); i++) - allTokens.put(wholeTokens.getString(i)); - for (int i = 0; i < partTokens.length(); i++) - allTokens.put(partTokens.getString(i)); - int intPart = wholeTokens.length(); - JSONArray wholeTokenContent = new JSONArray(); - for (int i = 0; i < intPart; i++) { - String TokenContent = get(wholeTokens.getString(i), ipfs); - wholeTokenContent.put(TokenContent); - } - - JSONArray partTokenContent = new JSONArray(); - for (int i = 0; i < partTokens.length(); i++) { - String TokenContent = get(partTokens.getString(i), ipfs); - partTokenContent.put(TokenContent); - } - JSONArray allTokensContent = new JSONArray(); - for (int i = 0; i < wholeTokenContent.length(); i++) { - allTokensContent.put(wholeTokenContent.getString(i)); - } - for (int i = 0; i < partTokenContent.length(); i++) { - allTokensContent.put(partTokenContent.getString(i)); - } - - boolean tokenMinedStatus = true; - String tokenMinedStatusErrorMessage = ""; - if (!EXPLORER_IP.contains("127.0.0.1")) { - TokenReceiverLogger.debug("Contacting Explorer ..." + EXPLORER_IP); - for (int i = 0; i < allTokensContent.length(); i++) { - - String token = allTokensContent.getString(i); - String url = EXPLORER_IP + "/check-mined-status/" + token; - URL obj = new URL(url); - HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); - - // Setting basic post request - con.setRequestMethod("GET"); - 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"); - - int responseCode = con.getResponseCode(); - TokenReceiverLogger.debug("Response Code : " + responseCode); - if (responseCode != 200) { - tokenMinedStatusErrorMessage = "Token Integrity Failed"; - TokenReceiverLogger.debug("Token Integrity Failed"); - tokenMinedStatus = false; - break; - } - - TokenReceiverLogger.debug("Reading status"); - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String responseOutput; - StringBuffer response = new StringBuffer(); - - while ((responseOutput = in.readLine()) != null) { - response.append(responseOutput); - } - in.close(); - JSONObject responseObject = new JSONObject(response.toString()); - System.out.println("Status for token " + token + ": " + responseObject.getBoolean("status")); - if (!responseObject.getBoolean("status")) { - tokenMinedStatusErrorMessage = responseObject.getString("message"); - tokenMinedStatus = false; - break; - } - } - } else { - tokenMinedStatusErrorMessage = "Could not contact explorer: Explorer IP (127.0.0.1)"; - tokenMinedStatus = false; - } - if (!tokenMinedStatus) { - TokenReceiverLogger.debug(tokenMinedStatusErrorMessage); - output.println("419"); - output.println(tokenMinedStatusErrorMessage); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", tokenMinedStatusErrorMessage); - IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } // Double decimalPart = formatAmount(amount - intPart); - JSONArray doubleSpentToken = new JSONArray(); - boolean tokenOwners = true; - ArrayList ownersArray = new ArrayList(); - ArrayList previousSender = new ArrayList(); - JSONArray ownersReceived = new JSONArray(); - for (int i = 0; i < wholeTokens.length(); ++i) { - try { - TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + " Please wait..."); - ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); - - if (ownersArray.size() > 2) { - - for (int j = 0; j < previousSendersArray.length(); j++) { - if (previousSendersArray.getJSONObject(j).getString("token") - .equals(wholeTokens.getString(i))) - ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); - } - - for (int j = 0; j < ownersReceived.length(); j++) { - previousSender.add(ownersReceived.getString(j)); - } - TokenReceiverLogger.debug("Previous Owners: " + previousSender); - - for (int j = 0; j < ownersArray.size(); j++) { - if (!previousSender.contains(ownersArray.get(j).toString())) - doubleSpentToken.put(wholeTokens.getString(i)); - tokenOwners = false; - } - } - } catch (IOException e) { - - TokenReceiverLogger.debug("Ipfs dht find did not execute"); - } - } - if (!tokenOwners) { - JSONArray owners = new JSONArray(); - for (int i = 0; i < ownersArray.size(); i++) - owners.put(ownersArray.get(i).toString()); - TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); - TokenReceiverLogger.debug("Owners: " + owners); - output.println("420"); - output.println(doubleSpentToken.toString()); - output.println(owners.toString()); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + owners); - IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } + // JSONArray doubleSpentToken = new JSONArray(); + // boolean tokenOwners = true; + // ArrayList ownersArray = new ArrayList(); + // ArrayList previousSender = new ArrayList(); + // JSONArray ownersReceived = new JSONArray(); + // for (int i = 0; i < wholeTokens.length(); ++i) { + // try { + // TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + + // " Please wait..."); + // ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); + // + // if (ownersArray.size() > 2) { + // + // for (int j = 0; j < previousSendersArray.length(); j++) { + // if + // (previousSendersArray.getJSONObject(j).getString("token").equals(wholeTokens.getString(i))) + // ownersReceived = + // previousSendersArray.getJSONObject(j).getJSONArray("sender"); + // } + // + // for (int j = 0; j < ownersReceived.length(); j++) { + // previousSender.add(ownersReceived.getString(j)); + // } + // TokenReceiverLogger.debug("Previous Owners: " + previousSender); + // + // for (int j = 0; j < ownersArray.size(); j++) { + // if (!previousSender.contains(ownersArray.get(j).toString())) + // tokenOwners = false; + // } + // } + // } catch (IOException e) { + // + // TokenReceiverLogger.debug("Ipfs dht find did not execute"); + // } + // } + // if (!tokenOwners) { + // JSONArray owners = new JSONArray(); + // for (int i = 0; i < ownersArray.size(); i++) + // owners.put(ownersArray.get(i).toString()); + // TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); + // TokenReceiverLogger.debug("Owners: " + owners); + // output.println("420"); + // output.println(doubleSpentToken.toString()); + // output.println(owners.toString()); + // APIResponse.put("did", senderDidIpfsHash); + // APIResponse.put("tid", "null"); + // APIResponse.put("status", "Failed"); + // APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + + // owners); + // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + // output.close(); + // input.close(); + // sk.close(); + // ss.close(); + // return APIResponse.toString(); + // } String senderToken = TokenDetails.toString(); String consensusID = calculateHash(senderToken, "SHA3-256"); writeToFile(LOGGER_PATH + "consensusID", consensusID, false); @@ -501,13 +410,13 @@ public static String receive() { String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); - // TokenReceiverLogger.debug("Ownership Here Sender Calculation"); - // TokenReceiverLogger.debug("tokens: " + tokens); - // TokenReceiverLogger.debug("hashString: " + hashString); - // TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - // TokenReceiverLogger.debug("p1: " + positionsArray.getString(i)); - // TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - // TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); + TokenReceiverLogger.debug("Ownership Here Sender Calculation"); + TokenReceiverLogger.debug("tokens: " + tokens); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); if (!owner.equals(ownerRecalculated)) { ownerCheck = false; @@ -854,7 +763,7 @@ public static String receive() { for (int i = 0; i < intPart; i++) { FileWriter fileWriter; fileWriter = new FileWriter(TOKENS_PATH + wholeTokens.getString(i)); - fileWriter.write(wholeTokenContent.getString(i)); + fileWriter.write(wholeTokenContent.get(i)); fileWriter.close(); add(TOKENS_PATH + wholeTokens.getString(i), ipfs); pin(wholeTokens.getString(i), ipfs); @@ -906,7 +815,7 @@ public static String receive() { .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); String firstPrivate = PropImage.img2bin(pvt); int[] privateIntegerArray1 = strToIntArray(firstPrivate); - String privateBinary = intArrayToStr(privateIntegerArray1); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); String positions = ""; for (int j = 0; j < privateIntegerArray1.length; j += 49152) { positions += privateBinary.charAt(j); @@ -914,13 +823,13 @@ public static String receive() { String ownerIdentity = hashForPositions.concat(positions); String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); - // TokenReceiverLogger.debug("Ownership Here"); - // TokenReceiverLogger.debug("tokens: " + wholeTokens.getString(i)); - // TokenReceiverLogger.debug("hashString: " + hashString); - // TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - // TokenReceiverLogger.debug("p1: " + positions); - // TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - // TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); + TokenReceiverLogger.debug("Ownership Here"); + TokenReceiverLogger.debug("tokens: " + wholeTokens.getString(i)); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positions); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); ArrayList groupTokens = new ArrayList<>(); for (int k = 0; k < intPart; k++) { @@ -965,7 +874,7 @@ public static String receive() { .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); String firstPrivate = PropImage.img2bin(pvt); int[] privateIntegerArray1 = strToIntArray(firstPrivate); - String privateBinary = intArrayToStr(privateIntegerArray1); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); String positions = ""; for (int j = 0; j < privateIntegerArray1.length; j += 49152) { positions += privateBinary.charAt(j); @@ -974,13 +883,13 @@ public static String receive() { String ownerIdentity = hashForPositions.concat(positions); String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); - // TokenReceiverLogger.debug("Ownership Here"); - // TokenReceiverLogger.debug("tokens: " + partTokens.getString(i)); - // TokenReceiverLogger.debug("hashString: " + hashString); - // TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - // TokenReceiverLogger.debug("p1: " + positions); - // TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - // TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); + TokenReceiverLogger.debug("Ownership Here"); + TokenReceiverLogger.debug("tokens: " + partTokens.getString(i)); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positions); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); JSONObject newPartObject = new JSONObject(); newPartObject.put("senderSign", senderSignature); @@ -1047,7 +956,7 @@ public static String receive() { JSONObject tokenObject1 = new JSONObject(); tokenObject1.put("tokenHash", wholeTokens.getString(i)); bankArray.put(tokenObject1); - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); + Functions.writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); } @@ -1126,7 +1035,9 @@ public static String receive() { 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(); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 7f38f176..c32b7336 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -10,7 +10,6 @@ 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.arrangeQuorum; import static com.rubix.Resources.Functions.calculateHash; import static com.rubix.Resources.Functions.deleteFile; import static com.rubix.Resources.Functions.formatAmount; @@ -386,7 +385,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception ArrayList betaPeersList; ArrayList gammaPeersList; - int arrangeCode = 0; JSONArray quorumArray; switch (type) { case 1: { @@ -405,7 +403,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception case 2: { quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); - arrangeCode = arrangeQuorum(quorumArray, port + 15, requestedAmount); break; } case 3: { @@ -421,27 +418,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } - if (arrangeCode == 401) { - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - String message = "Could not collect all(min. 21) credits"; - APIResponse.put("message", message); - TokenSenderLogger.warn(message); - return APIResponse; - } else if (arrangeCode == 402) { - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - String message = "7 alpha node credits not summing up to requested amount"; - APIResponse.put("message", message); - TokenSenderLogger.warn(message); - senderMutex = false; - return APIResponse; - } else if (arrangeCode == 200) { - quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); - } - int alphaCheck = 0, betaCheck = 0, gammaCheck = 0; JSONArray sanityFailedQuorum = new JSONArray(); for (int i = 0; i < quorumArray.length(); i++) { @@ -467,7 +443,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String message = "Quorum: ".concat(sanityFailedQuorum.toString()).concat(" "); APIResponse.put("message", message.concat(sanityMessage)); TokenSenderLogger.warn("Quorum: ".concat(message.concat(sanityMessage))); - senderMutex = false; return APIResponse; } @@ -492,7 +467,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception endTime = System.currentTimeMillis(); totalTime = endTime - startTime; - eventLogger.debug("Quorum check " + totalTime); + eventLogger.debug("Quorum Check " + totalTime); if (alphaPeersList.size() < minQuorum(alphaSize) || betaPeersList.size() < 5 || gammaPeersList.size() < 5) { updateQuorum(quorumArray, null, false, type); @@ -673,12 +648,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } if (tokenAuth != null && (tokenAuth.startsWith("4"))) { switch (tokenAuth) { - case "419": - String tokenAuthErrorMessage = input.readLine(); - TokenSenderLogger.info(tokenAuthErrorMessage); - TokenSenderLogger.info("Kindly re-initiate transaction later or with another token"); - APIResponse.put("message", tokenAuthErrorMessage + " Kindly re-initiate transaction"); - break; case "420": String doubleSpent = input.readLine(); String owners = input.readLine(); @@ -705,8 +674,8 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception case "424": String invalidTokens = input.readLine(); JSONArray tokensArray = new JSONArray(invalidTokens); - TokenSenderLogger.info("Ownership check Failed for " + tokensArray); - APIResponse.put("message", "Ownership check Failed"); + TokenSenderLogger.info("Ownership Check Failed for " + tokensArray); + APIResponse.put("message", "Ownership Check Failed"); break; case "425": @@ -728,6 +697,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("status", "Failed"); return APIResponse; } + TokenSenderLogger.debug("Token Auth Code: " + tokenAuth); JSONObject dataObject = new JSONObject(); dataObject.put("tid", tid); From aa5cfa314c0edbdbf2d82458d3d5fbf97a0c08d0 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sat, 26 Mar 2022 12:53:48 +0530 Subject: [PATCH 042/179] QST duplicate check Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index bd102c73..e2656347 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -283,11 +283,11 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // "/PrivateShare.png", // mineDetToSign.getString(MINE_ID))); - FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mystake.txt"), + FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "stake.txt"), true); shareWriter.write(genesisBlock.toString()); shareWriter.close(); - File readStake = new File(LOGGER_PATH + "mystake.txt"); + File readStake = new File(LOGGER_PATH + "stake.txt"); String mineID = add(readStake.toString(), ipfs); pin(mineID, ipfs); @@ -314,7 +314,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // QuorumConsensusLogger.debug("Quorum Share: " + credit); // updateJSON("add", WALLET_DATA_PATH + "QuorumSignedTransactions.json", // data.toString()); - deleteFile(LOGGER_PATH + "mystake.txt"); + deleteFile(LOGGER_PATH + "stake.txt"); stakingSigns.put(MINE_ID, mineID); @@ -475,6 +475,16 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", JSONArray creditsArray = qstObject.getJSONArray("credits"); boolean flag = true; + // if qstArray has any duplicate object + for (int i = 0; i < qstArray.length(); i++) { + for (int j = i + 1; j < qstArray.length(); j++) { + if (qstArray.getJSONObject(i).getString("qst") + .equals(qstArray.getJSONObject(j).getString("qst"))) { + flag = false; + break; + } + } + } for (int i = 0; i < creditsRequired; i++) { QuorumConsensusLogger.debug("Credit object: " + creditsArray.getJSONObject(i).toString()); QuorumConsensusLogger.debug( @@ -487,6 +497,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", flag = false; } } + if (flag) { boolean verifySigns = true; From 46ebaaf88b0f2f203452104ea70872ed5ffa392c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sat, 26 Mar 2022 12:56:00 +0530 Subject: [PATCH 043/179] fix: credit duplicate check Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index e2656347..3abe7992 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -478,8 +478,8 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // if qstArray has any duplicate object for (int i = 0; i < qstArray.length(); i++) { for (int j = i + 1; j < qstArray.length(); j++) { - if (qstArray.getJSONObject(i).getString("qst") - .equals(qstArray.getJSONObject(j).getString("qst"))) { + if (qstArray.getJSONObject(i).getString("credits") + .equals(qstArray.getJSONObject(j).getString("credits"))) { flag = false; break; } From 70836a9b38cfb91ff8584a22cc5f5fadf0d88696 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 28 Mar 2022 15:41:31 +0530 Subject: [PATCH 044/179] fixed: staking timeout Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- src/com/rubix/Resources/Functions.java | 25 ++++++++++++++++++++ src/com/rubix/TokenTransfer/TokenSender.java | 2 ++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 34837cd5..35f8b39c 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -31,7 +31,7 @@ public class StakeConsensus { public static Logger StakeConsensusLogger = Logger.getLogger(StakeConsensus.class); - private static int socketTimeOut = 120000; + private static int socketTimeOut = 1800000; private static volatile boolean STAKE_SUCCESS = false; public static volatile JSONObject stakeDetails = new JSONObject(); // MINE_ID diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 7a702ac6..e84a33a6 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1151,6 +1151,31 @@ public static void syncDataTable(String did, String peerId) { } } + /** + * To Sync DataTable.json, if required + */ + public static void syncDataTableByDID(String did) { + 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))) { + isObjectValid = true; + break; + } + } + if (!isObjectValid) { + FunctionsLogger.debug("Syncing Datatable.json!"); + APIHandler.networkInfo(); + } + } catch (Exception e) { + FunctionsLogger.error("Exception Occured", e); + e.printStackTrace(); + } + } + public static void correctToken() throws JSONException { pathSet(); String bank = readFile(PAYMENTS_PATH.concat("BNK00.json")); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index c32b7336..3726a96e 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -26,6 +26,7 @@ import static com.rubix.Resources.Functions.sanityMessage; import static com.rubix.Resources.Functions.strToIntArray; import static com.rubix.Resources.Functions.syncDataTable; +import static com.rubix.Resources.Functions.syncDataTableByDID; import static com.rubix.Resources.Functions.updateJSON; import static com.rubix.Resources.Functions.updateQuorum; import static com.rubix.Resources.Functions.writeToFile; @@ -99,6 +100,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception JSONObject detailsObject = new JSONObject(data); String receiverDidIpfsHash = detailsObject.getString("receiverDidIpfsHash"); + syncDataTableByDID(receiverDidIpfsHash); String receiverPeerId = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", receiverDidIpfsHash); String pvt = detailsObject.getString("pvt"); double requestedAmount = detailsObject.getDouble("amount"); From 601f2261f4bc316272b1e382ff6c91729b389059 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 28 Mar 2022 18:27:45 +0530 Subject: [PATCH 045/179] wait for quorum to finish Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 35f8b39c..6503a0fa 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -191,7 +191,6 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } if (mineSignCheck) { - // ! send credits StakeConsensusLogger.debug( "%%%%%%%%||||||||||||########--Staking Complete! Sending Credits--###########|||||||||||||%%%%%%%%%%%"); @@ -222,7 +221,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject }); quorumThreads[j].start(); } - ; + do { + + } while (!STAKE_SUCCESS); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); From 3a1e1c50e775d424d3eba10013b643bc2ae2b36a Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 28 Mar 2022 19:10:47 +0530 Subject: [PATCH 046/179] fix qsContent object Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 10 ++++++---- src/com/rubix/Mining/ProofCredits.java | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 3abe7992..728f9d8f 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -166,7 +166,8 @@ public void run() { response_credit.append(inputLine_credit); } in_credit.close(); - QuorumConsensusLogger.debug("response from service " + response_credit.toString()); + // QuorumConsensusLogger.debug("response from service " + + // response_credit.toString()); JSONObject resJsonData_credit = new JSONObject(response_credit.toString()); int level_credit = resJsonData_credit.getInt("level"); int creditsRequired = (int) Math.pow(2, (2 + level_credit)); @@ -184,10 +185,10 @@ public void run() { if (genesisBlock.has("quorumSignatures")) { int randomNumber = new Random().nextInt(15); - JSONArray genesisSignatures = genesisBlock.getJSONArray("quorumSignContent"); + JSONObject genesisSignatures = genesisBlock.getJSONObject("quorumSignContent"); try { - JSONObject VerificationPick = genesisSignatures.getJSONObject(randomNumber); + JSONObject VerificationPick = genesisSignatures.getJSONObject(String.valueOf(randomNumber)); if (VerificationPick.getString("hash") == genesisBlock.getString("tid")) { if (Authenticate.verifySignature(VerificationPick.toString())) { @@ -461,7 +462,8 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", response_credit.append(inputLine_credit); } in_credit.close(); - QuorumConsensusLogger.debug("response from service " + response_credit.toString()); + // QuorumConsensusLogger.debug("response from service " + + // response_credit.toString()); resJsonData_credit = new JSONObject(response_credit.toString()); int level_credit = resJsonData_credit.getInt("level"); creditsRequired = (int) Math.pow(2, (2 + level_credit)); diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 1a41327a..dcc148a9 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -118,7 +118,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON response_credit.append(inputLine_credit); } in_credit.close(); - ProofCreditsLogger.debug("response from service " + response_credit.toString()); + // ProofCreditsLogger.debug("response from service " + + // response_credit.toString()); resJsonData_credit = new JSONObject(response_credit.toString()); int level_credit = resJsonData_credit.getInt("level"); creditsRequired = (int) Math.pow(2, (2 + level_credit)); @@ -153,7 +154,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON response.append(inputLine); } in.close(); - ProofCreditsLogger.debug("response from service " + response.toString()); + // ProofCreditsLogger.debug("response from service " + response.toString()); resJsonData = new JSONArray(response.toString()); } else From ce92f9b08be99e94c970a465f3384058cafe0a78 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 28 Mar 2022 21:22:24 +0530 Subject: [PATCH 047/179] fix signContent Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 26 ++++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 728f9d8f..cbbd503c 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -184,24 +184,24 @@ public void run() { // ! validate mined token hash and ownership if (genesisBlock.has("quorumSignatures")) { - int randomNumber = new Random().nextInt(15); - JSONObject genesisSignatures = genesisBlock.getJSONObject("quorumSignContent"); try { + int randomNumber = new Random().nextInt(15); + JSONObject genesisSignatures = genesisBlock.getJSONObject("quorumSignContent"); + JSONArray keys = genesisSignatures.names(); + String signer = keys.getString(randomNumber); + String signature = genesisSignatures.getString(signer); - JSONObject VerificationPick = genesisSignatures.getJSONObject(String.valueOf(randomNumber)); - if (VerificationPick.getString("hash") == genesisBlock.getString("tid")) { + JSONObject VerificationPick = new JSONObject(); + VerificationPick.put("signature", signature); + VerificationPick.put("did", signer); + VerificationPick.put("hash", genesisSignatures.getString("tid")); - if (Authenticate.verifySignature(VerificationPick.toString())) { - - QuorumConsensusLogger.debug("Validated signature of newly minted token"); - isValid = true; - } else { - QuorumConsensusLogger.debug("Signature not verified"); - isValid = false; - } + if (Authenticate.verifySignature(VerificationPick.toString())) { + QuorumConsensusLogger.debug("Validated signature of newly minted token"); + isValid = true; } else { - QuorumConsensusLogger.debug("Mined token quorum signature hash not matched"); + QuorumConsensusLogger.debug("Signature not verified"); isValid = false; } } catch (Exception e) { From 5a8d30425824d94b158e039aeba9df3ac5d83f7f Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 28 Mar 2022 22:52:23 +0530 Subject: [PATCH 048/179] private share image path Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index cbbd503c..c64454f3 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -240,7 +240,7 @@ public void run() { String hashForPositions = calculateHash(hashString, "SHA3-256"); BufferedImage privateShare = ImageIO .read(new File( - DATA_PATH.concat(senderDidIpfsHash).concat("/PrivateShare.png"))); + DATA_PATH.concat(didHash).concat("/PrivateShare.png"))); String firstPrivate = PropImage.img2bin(privateShare); int[] privateIntegerArray1 = strToIntArray(firstPrivate); String privateBinary = Functions.intArrayToStr(privateIntegerArray1); From 42f9f29ce85435a0f5018180697e784f98eb07c7 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 29 Mar 2022 10:13:57 +0530 Subject: [PATCH 049/179] fixed err messages in staking Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 3 ++- src/com/rubix/Consensus/StakeConsensus.java | 12 ++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index c64454f3..6e9c326f 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -206,7 +206,8 @@ public void run() { } } catch (Exception e) { QuorumConsensusLogger - .debug("Mined token quorum signature hash not found in IPFS. Skipping..."); + .debug("Mined Token - Quorum Signature Hash not found. Skipping... Exception: " + + e.getMessage()); // isValid = false; } diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 6503a0fa..70a7ec8b 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -204,12 +204,20 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } } else if (qResponse[j].equals("444")) { - StakeConsensusLogger.debug("Error response from staker (insuff). Skipping..."); + StakeConsensusLogger.debug("Quorum could not verify mined token. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("445")) { + StakeConsensusLogger.debug("Insufficient quorum member balance. Skipping..."); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + } else if (qResponse[j].equals("446")) { + StakeConsensusLogger + .debug("Token files picked by quorum to stake is corroupted. Skipping..."); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + } else if (qResponse[j].equals("447")) { + StakeConsensusLogger.debug("alpha-stake-token-not-verified. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else { - StakeConsensusLogger.debug("Error response from staker. Skipping..."); + StakeConsensusLogger.debug("Unexpected response from staker: " + qResponse[j]); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } From c135d52984995571d1ebe4c7211466dac4c54318 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 29 Mar 2022 12:10:16 +0530 Subject: [PATCH 050/179] fix socket res validation Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 70a7ec8b..6fc4e763 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -99,7 +99,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .debug("Mined Token Details validation failed. Received null response"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } - if (!qResponse[j].contains("44")) { + if (qResponse[j].length() > 3) { StakeConsensusLogger .debug("Mined Token Details validated. Received staked token details.."); From abdbd9873d5356524fbfd2f5440e9eff611e96a3 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 29 Mar 2022 13:25:06 +0530 Subject: [PATCH 051/179] fix bnk Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 25 +++++++------------ .../rubix/TokenTransfer/TokenReceiver.java | 4 --- 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 6e9c326f..54f64008 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -1,8 +1,10 @@ package com.rubix.Consensus; import static com.rubix.Constants.ConsensusConstants.INIT_HASH; +import static com.rubix.Constants.MiningConstants.MINED_RBT; import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; import static com.rubix.Constants.MiningConstants.MINE_ID; +import static com.rubix.Constants.MiningConstants.MINE_TID; import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Resources.Functions.DATA_PATH; @@ -223,10 +225,12 @@ public void run() { if (bankArray.length() != 0) { - // pick last object from bank array JSONObject bankObject = bankArray.getJSONObject(0); String tokenHash = bankObject.getString("tokenHash"); tokenToStake.put(tokenHash); + bankArray.remove(0); + bankArray.put(bankObject); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); File tokenFile = new File(TOKENS_PATH + tokenHash); File tokenchainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); @@ -235,7 +239,8 @@ public void run() { if (tokenFile.exists() && tokenchainFile.exists()) { String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); - tokenToStake.put(tokenChain); + JSONArray tokenChainArray = new JSONArray(tokenChain); + tokenToStake.put(tokenChainArray); String hashString = tokenHash.concat(senderDidIpfsHash); String hashForPositions = calculateHash(hashString, "SHA3-256"); @@ -275,9 +280,11 @@ STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", genesisBlock.getString("tid"))); + stakingSigns.put(MINE_TID, genesisBlock.getString("tid")); stakingSigns.put( MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", genesisBlock.getString("tokenHash"))); + stakingSigns.put(MINED_RBT, genesisBlock.getString("tokenHash")); genesisBlock.put("stakerSignatures", stakingSigns); @@ -327,20 +334,6 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // ! receive credits equal to credits required to mine token - String credits = null; - try { - credits = in.readLine(); - // convert mineData to JSONObject - System.out.println("credits received " + credits); - } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - Adding Credits Failed"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - - System.out.println("credits received " + credits); - // JSONArray creditArray = new JSONArray(credits); // // Get level of token from advisory node diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 9eec6f97..38704609 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -569,10 +569,6 @@ public static String receive() { ownerCheck = false; invalidTokens.put(tokens); } - } else if (lastObject.length() == 0) { - TokenReceiverLogger.debug("Staking check failed: No Token Chain data found for token: " + tokens); - // ownerCheck = false; - // invalidTokens.put(tokens); } // ! staking checks ends here } From d1852afa4486e3aee6d19cc72175fcf0dc298e10 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 29 Mar 2022 14:19:19 +0530 Subject: [PATCH 052/179] TC type error Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 5 ++++- src/com/rubix/Consensus/StakeConsensus.java | 5 ++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 54f64008..73f9e4f3 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -238,6 +238,8 @@ public void run() { // check if token file and tokenchain file exists if (tokenFile.exists() && tokenchainFile.exists()) { + QuorumConsensusLogger.debug("Token and TokenChain files found"); + String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); JSONArray tokenChainArray = new JSONArray(tokenChain); tokenToStake.put(tokenChainArray); @@ -390,13 +392,14 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } else { - QuorumConsensusLogger.debug("Token file not found"); + QuorumConsensusLogger.debug("Token to stake not verified"); out.println("447"); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } } else { + QuorumConsensusLogger.debug("Token to stake not found"); out.println("446"); socket.close(); serverSocket.close(); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 6fc4e763..b28ee9a2 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -108,14 +108,13 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject quorumPID[j]); JSONArray stakeTokenArray = new JSONArray(qResponse[j]); String stakeTokenHash = stakeTokenArray.getString(0); - String stakeTCObject = stakeTokenArray.getString(1); + JSONArray stakeTC = stakeTokenArray.getJSONArray(1); String positionsArray = stakeTokenArray.getString(2); - JSONArray stakeTC = new JSONArray(stakeTCObject); // ! check ownership of stakeTC from Token Receiver logic if (stakeTC.length() > 0 && stakeTokenHash != null && positionsArray != null) { - JSONObject lastObject = stakeTC.getJSONObject(stakeTCObject.length() - 1); + JSONObject lastObject = stakeTC.getJSONObject(stakeTC.length() - 1); StakeConsensusLogger.debug("Last Object = " + lastObject); if (lastObject.has("owner")) { StakeConsensusLogger.debug("Checking ownership"); From 8008e52dfcce9907bcf6d40cda036bd436625135 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 29 Mar 2022 16:43:29 +0530 Subject: [PATCH 053/179] extra checks before exiting staking Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 2 ++ src/com/rubix/Consensus/StakeConsensus.java | 22 +++++++++++++------- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 73f9e4f3..88501662 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -262,6 +262,8 @@ public void run() { try { response = in.readLine(); + QuorumConsensusLogger + .debug("Staking response after verifying staked token: " + response); } catch (SocketException e) { QuorumConsensusLogger .debug("Sender Input Stream Null - Stake Token Validation by Miner Failed"); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index b28ee9a2..262d79f6 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -32,6 +32,7 @@ public class StakeConsensus { public static Logger StakeConsensusLogger = Logger.getLogger(StakeConsensus.class); private static int socketTimeOut = 1800000; + private static volatile boolean STAKE_LOCKED = false; private static volatile boolean STAKE_SUCCESS = false; public static volatile JSONObject stakeDetails = new JSONObject(); // MINE_ID @@ -114,10 +115,14 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject // ! check ownership of stakeTC from Token Receiver logic if (stakeTC.length() > 0 && stakeTokenHash != null && positionsArray != null) { + JSONObject lastObject = stakeTC.getJSONObject(stakeTC.length() - 1); StakeConsensusLogger.debug("Last Object = " + lastObject); if (lastObject.has("owner")) { - StakeConsensusLogger.debug("Checking ownership"); + StakeConsensusLogger + .debug("Checking ownership of " + stakeTokenHash + " from DID " + + lastObject.getString("owner") + " for positions send: " + + positionsArray); String owner = lastObject.getString("owner"); String tokens = stakeTokenHash; String hashString = tokens.concat(stakerDID); @@ -135,7 +140,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject if (!owner.equals(ownerRecalculated)) { ownerCheck = false; - StakeConsensusLogger.debug("Ownership Check Failed"); + StakeConsensusLogger.debug( + "Ownership Check Failed for index " + j + " with DID: " + owner); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } @@ -144,9 +150,10 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } - if (ownerCheck && !STAKE_SUCCESS) { - StakeConsensusLogger.debug("Ownership Check Success for: PID" + quorumPID[j]); - STAKE_SUCCESS = true; + if (ownerCheck && !STAKE_LOCKED) { + StakeConsensusLogger.debug("Ownership Check Success for Peer: " + quorumPID[j]); + STAKE_LOCKED = true; + StakeConsensusLogger.debug("Staking locked with for Peer: " + quorumPID[j]); qOut[j].println("alpha-stake-token-verified"); StakeConsensusLogger.debug("Waiting for stake signatures"); @@ -159,7 +166,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .debug("Mined Token Details validation failed. Received null response"); } - if (!qResponse[j].contains("44")) { + if (qResponse[j].length() > 3) { // ! add mine signs to tokenchain StakeConsensusLogger.debug("Adding mine signatures"); @@ -194,6 +201,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject "%%%%%%%%||||||||||||########--Staking Complete! Sending Credits--###########|||||||||||||%%%%%%%%%%%"); qOut[j].println("staking-completed"); + STAKE_SUCCESS = true; } } @@ -230,7 +238,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } do { - } while (!STAKE_SUCCESS); + } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() > 0); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); From 939244bbac9ec37783c4ce1c7a62bbd26c50c619 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 29 Mar 2022 18:50:07 +0530 Subject: [PATCH 054/179] hold PC for completing staking Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 4 ++-- src/com/rubix/Mining/ProofCredits.java | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 262d79f6..4615d37c 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -198,7 +198,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject if (mineSignCheck) { StakeConsensusLogger.debug( - "%%%%%%%%||||||||||||########--Staking Complete! Sending Credits--###########|||||||||||||%%%%%%%%%%%"); + "%%%%%%%%||||||||||||########--Staking Complete!--###########|||||||||||||%%%%%%%%%%%"); qOut[j].println("staking-completed"); STAKE_SUCCESS = true; @@ -238,7 +238,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } do { - } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() > 0); + } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 4); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index dcc148a9..edbf0287 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -421,6 +421,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject, ipfs, SEND_PORT + 3, "alpha-stake-token"); + do { + + } while (StakeConsensus.stakeDetails.length() < 4); + if (StakeConsensus.stakeDetails.length() > 0) { tokenChainArray.put(StakeConsensus.stakeDetails); } else { From f19344810418b3c7dcf0cc1187717f097ace8c9d Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 30 Mar 2022 11:49:47 +0530 Subject: [PATCH 055/179] Fix .equals() instead of == Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 6 +++--- src/com/rubix/Consensus/StakeConsensus.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 88501662..d6becfaa 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -272,7 +272,7 @@ public void run() { executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - if (response == "alpha-stake-token-verified") { + if (response.equals("alpha-stake-token-verified")) { JSONObject stakingSigns = new JSONObject(); @@ -441,7 +441,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // Verify QST Credits JSONObject qstObject = new JSONObject(getNewCreditsData); - if (qstObject.getString(INIT_HASH) == initHash()) { + if (qstObject.getString(INIT_HASH).equals(initHash())) { // Get level of token from advisory node int creditsRequired = 0; @@ -572,7 +572,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", transactionID = readSenderData.getString("Tid"); verifySenderHash = readSenderData.getString("Hash"); receiverDID = readSenderData.getString("RID"); - initHash = readSenderData.getString(INIT_HASH); + // initHash = readSenderData.getString(INIT_HASH); syncDataTable(senderDidIpfsHash, null); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 4615d37c..fd091a2a 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -198,7 +198,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject if (mineSignCheck) { StakeConsensusLogger.debug( - "%%%%%%%%||||||||||||########--Staking Complete!--###########|||||||||||||%%%%%%%%%%%"); + "########--Staking Complete!--###########"); qOut[j].println("staking-completed"); STAKE_SUCCESS = true; From 59e0bc2141e4f3d731302a8d9c1ad022669b39b3 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 30 Mar 2022 13:48:38 +0530 Subject: [PATCH 056/179] extra logs Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 6 +++++- src/com/rubix/Mining/ProofCredits.java | 5 +++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index fd091a2a..7f1d9f70 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -166,7 +166,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .debug("Mined Token Details validation failed. Received null response"); } - if (qResponse[j].length() > 3) { + if (qResponse[j].length() == 6) { // ! add mine signs to tokenchain StakeConsensusLogger.debug("Adding mine signatures"); @@ -204,6 +204,10 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject STAKE_SUCCESS = true; } + } else { + StakeConsensusLogger.debug( + "Stake signatures not received.. Quorum response: " + qResponse[j]); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } else { StakeConsensusLogger.debug("Ownership Check Failed"); diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index edbf0287..8feff20f 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -423,10 +423,11 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON do { - } while (StakeConsensus.stakeDetails.length() < 4); + } while (StakeConsensus.stakeDetails.length() < 6); - if (StakeConsensus.stakeDetails.length() > 0) { + if (StakeConsensus.stakeDetails.length() == 6) { tokenChainArray.put(StakeConsensus.stakeDetails); + ProofCreditsLogger.debug("Stake Details for new mined token: " + StakeConsensus.stakeDetails); } else { updateQuorum(quorumArray, null, false, type); APIResponse.put("did", DID); From b4e418d925b7c127b9669eabd01f68c9d1c23b3c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 30 Mar 2022 16:30:07 +0530 Subject: [PATCH 057/179] rm while loop in PC Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/ProofCredits.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 8feff20f..30201c1f 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -421,9 +421,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject, ipfs, SEND_PORT + 3, "alpha-stake-token"); - do { - - } while (StakeConsensus.stakeDetails.length() < 6); + // do { + // } while (StakeConsensus.stakeDetails.length() < 6); if (StakeConsensus.stakeDetails.length() == 6) { tokenChainArray.put(StakeConsensus.stakeDetails); From ea6e8183182c67845247cf025de4d662177b0d2e Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 30 Mar 2022 16:49:47 +0530 Subject: [PATCH 058/179] sign length condition in stake consensus Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 2 +- src/com/rubix/Consensus/StakeConsensus.java | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index d6becfaa..87ca7386 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -331,7 +331,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", stakingSigns.put(MINE_ID, mineID); - QuorumConsensusLogger.debug("Staking Token Staked Successfully. MINE ID: " + + QuorumConsensusLogger.debug("Token Staked Successfully. MINE ID: " + mineID); out.println(stakingSigns.toString()); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 7f1d9f70..f5378922 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -166,11 +166,11 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .debug("Mined Token Details validation failed. Received null response"); } - if (qResponse[j].length() == 6) { + // ! add mine signs to tokenchain + StakeConsensusLogger.debug("Adding mine signatures"); + JSONObject mineSigns = new JSONObject(qResponse[j]); - // ! add mine signs to tokenchain - StakeConsensusLogger.debug("Adding mine signatures"); - JSONObject mineSigns = new JSONObject(qResponse[j]); + if (mineSigns.length() > 0) { stakeDetails = mineSigns; From d0d92e1318994c6b9fe0eda2daca4fa97d173eb2 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 31 Mar 2022 14:08:10 +0530 Subject: [PATCH 059/179] fix rec check 1/2 Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 104 ++++-------------- src/com/rubix/Constants/MiningConstants.java | 1 + .../rubix/TokenTransfer/TokenReceiver.java | 47 ++++---- 3 files changed, 45 insertions(+), 107 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 87ca7386..e15b211e 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -2,10 +2,12 @@ import static com.rubix.Constants.ConsensusConstants.INIT_HASH; import static com.rubix.Constants.MiningConstants.MINED_RBT; -import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; +import static com.rubix.Constants.MiningConstants.*; import static com.rubix.Constants.MiningConstants.MINE_ID; import static com.rubix.Constants.MiningConstants.MINE_TID; import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; +import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; +import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.IPFS_PORT; @@ -226,25 +228,25 @@ public void run() { if (bankArray.length() != 0) { JSONObject bankObject = bankArray.getJSONObject(0); - String tokenHash = bankObject.getString("tokenHash"); - tokenToStake.put(tokenHash); + String stakedTokenHash = bankObject.getString("tokenHash"); + tokenToStake.put(stakedTokenHash); bankArray.remove(0); bankArray.put(bankObject); writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); - File tokenFile = new File(TOKENS_PATH + tokenHash); - File tokenchainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); + File tokenFile = new File(TOKENS_PATH + stakedTokenHash); + File tokenchainFile = new File(TOKENCHAIN_PATH + stakedTokenHash + ".json"); // check if token file and tokenchain file exists if (tokenFile.exists() && tokenchainFile.exists()) { QuorumConsensusLogger.debug("Token and TokenChain files found"); - String tokenChain = readFile(TOKENCHAIN_PATH + tokenHash + ".json"); + String tokenChain = readFile(TOKENCHAIN_PATH + stakedTokenHash + ".json"); JSONArray tokenChainArray = new JSONArray(tokenChain); tokenToStake.put(tokenChainArray); - String hashString = tokenHash.concat(senderDidIpfsHash); + String hashString = stakedTokenHash.concat(senderDidIpfsHash); String hashForPositions = calculateHash(hashString, "SHA3-256"); BufferedImage privateShare = ImageIO .read(new File( @@ -275,22 +277,27 @@ public void run() { if (response.equals("alpha-stake-token-verified")) { JSONObject stakingSigns = new JSONObject(); - + // staker DID + stakingSigns.put(STAKED_QUORUM_DID, didHash); + // staked token and sign from staker + stakingSigns.put(STAKED_TOKEN, stakedTokenHash); stakingSigns.put( STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - tokenHash)); + stakedTokenHash)); + // tid and sign from staker + stakingSigns.put(MINE_TID, genesisBlock.getString("tid")); stakingSigns.put( MINING_TID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", genesisBlock.getString("tid"))); - stakingSigns.put(MINE_TID, genesisBlock.getString("tid")); + // mined token and sign from staker + stakingSigns.put(MINED_RBT, genesisBlock.getString("tokenHash")); stakingSigns.put( MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", genesisBlock.getString("tokenHash"))); - stakingSigns.put(MINED_RBT, genesisBlock.getString("tokenHash")); - genesisBlock.put("stakerSignatures", stakingSigns); + genesisBlock.put(STAKE_DATA, stakingSigns); // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + // "/PrivateShare.png", @@ -310,83 +317,19 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", stakeFile.createNewFile(); writeToFile(stakeFile.toString(), genesisBlock.toString(), false); - // QuorumConsensusLogger.debug("Credit object: " + credit); - // QuorumConsensusLogger.debug("Credit Hash: " + calculateHash(credit, - // "SHA3-256")); - // JSONObject storeDetailsQuorum = new JSONObject(); - // storeDetailsQuorum.put("tid", transactionID); - // storeDetailsQuorum.put("consensusID", verifySenderHash); - // storeDetailsQuorum.put("sign", senderPrivatePos); - // storeDetailsQuorum.put("credits", credit); - // storeDetailsQuorum.put("creditHash", calculateHash(credit, "SHA3-256")); - // storeDetailsQuorum.put("senderdid", senderDidIpfsHash); - // storeDetailsQuorum.put("Date", Functions.getCurrentUtcTime()); - // 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 + "stake.txt"); + // mine ID stakingSigns.put(MINE_ID, mineID); QuorumConsensusLogger.debug("Token Staked Successfully. MINE ID: " + mineID); out.println(stakingSigns.toString()); + tokenChainArray.put(stakingSigns); + writeToFile(TOKENCHAIN_PATH + stakedTokenHash + ".json", tokenChainArray.toString(), + false); - // ! receive credits equal to credits required to mine token - - // JSONArray creditArray = new JSONArray(credits); - - // // Get level of token from advisory node - // int creditsRequired = 0; - // JSONObject resJsonData_credit = new JSONObject(); - // String GET_URL_credit = SYNC_IP + "/getlevel"; - // URL URLobj_credit = new URL(GET_URL_credit); - // HttpURLConnection con_credit = (HttpURLConnection) - // URLobj_credit.openConnection(); - // con_credit.setRequestMethod("GET"); - // int responseCode_credit = con_credit.getResponseCode(); - // System.out.println("GET Response Code :: " + responseCode_credit); - // if (responseCode_credit == HttpURLConnection.HTTP_OK) { - // BufferedReader in_credit = new BufferedReader( - // new InputStreamReader(con_credit.getInputStream())); - // String inputLine_credit; - // StringBuffer response_credit = new StringBuffer(); - // while ((inputLine_credit = in_credit.readLine()) != null) { - // response_credit.append(inputLine_credit); - // } - // in_credit.close(); - // QuorumConsensusLogger - // .debug("response from service " + response_credit.toString()); - // resJsonData_credit = new JSONObject(response_credit.toString()); - // int level_credit = resJsonData_credit.getInt("level"); - // creditsRequired = (int) Math.pow(2, (2 + level_credit)); - // QuorumConsensusLogger.debug("credits required " + creditsRequired); - - // } else - // QuorumConsensusLogger.debug("GET request not worked"); - - // if (!(creditArray.length() != creditsRequired) && !(creditsRequired != 0)) { - - // QuorumConsensusLogger.debug("Credits received"); - // out.println("200"); - // socket.close(); - // serverSocket.close(); - // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - - // // ! store the credits - - // } else { - - // QuorumConsensusLogger.debug("Credits not received"); - // out.println("448"); - // socket.close(); - // serverSocket.close(); - // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - // } QuorumConsensusLogger.debug("Staking Completed!"); out.println("200"); socket.close(); @@ -500,7 +443,6 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", } if (flag) { - boolean verifySigns = true; for (int i = 0; i < creditsRequired; i++) { if (!Authenticate.verifySignature(creditsArray.getJSONObject(i).toString())) diff --git a/src/com/rubix/Constants/MiningConstants.java b/src/com/rubix/Constants/MiningConstants.java index 5b47c4d9..5339da50 100644 --- a/src/com/rubix/Constants/MiningConstants.java +++ b/src/com/rubix/Constants/MiningConstants.java @@ -6,6 +6,7 @@ public class MiningConstants { public static final String MINED_RBT = "minedToken"; public static final String MINE_ID = "mineID"; public static final String STAKED_QUORUM_DID = "stakedQuorumDID"; + public static final String STAKE_DATA = "stakeData"; public static final String STAKED_TOKEN = "stakedToken"; public static final String STAKED_TOKEN_SIGN = "stakedTokenSignature"; public static final String MINING_TID_SIGN = "TIDSignature"; diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 38704609..50234fb0 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -1,5 +1,10 @@ package com.rubix.TokenTransfer; +import static com.rubix.Constants.MiningConstants.MINE_ID; +import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; +import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; +import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; +import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.FunctionsLogger; import static com.rubix.Resources.Functions.IPFS_PORT; @@ -466,29 +471,26 @@ public static String receive() { int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); int tokenNumber = 1200001; - if (ownerCheck && (tokenChain.length() < tokenLevelValue) && (tokenLevelInt < 4) + if (ownerCheck && (tokenChain.length() < tokenLevelValue) && (tokenLevelInt >= 4) && (tokenNumber > 1200000)) { // ! staking checks (2): For incoming new mint token, verify the staked token JSONObject secondObject = tokenChain.getJSONObject(1); - String stakedTokenTC = secondObject.getString("stakedToken"); - String stakedTokenSignTC = secondObject.getString("stakedTokenSignature"); - String stakerDIDTC = secondObject.getString("stakerDID"); - String stakerDIDSignTC = secondObject.getString("stakerDIDSignature"); - String mineIDTC = secondObject.getString("mineID"); - String mineIDSignTC = secondObject.getString("mineIDSignature"); + String stakedTokenTC = secondObject.getString(STAKED_TOKEN); + String stakedTokenSignTC = secondObject.getString(STAKED_TOKEN_SIGN); + String stakerDIDTC = secondObject.getString(STAKED_QUORUM_DID); + String mineIDTC = secondObject.getString(MINE_ID); + String mineIDSignTC = secondObject.getString(MINE_ID_SIGN); String mineIDContent = get(mineIDTC, ipfs); JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - String stakerDIDMineData = mineIDContentJSON.getString("stakerDID"); - String stakerDIDSignMineData = mineIDContentJSON.getString("stakerDID"); - String stakedTokenMineData = mineIDContentJSON.getString("stakedToken"); - String stakedTokenSignMineData = mineIDContentJSON.getString("stakedToken"); + String stakerDIDMineData = mineIDContentJSON.getString(STAKED_QUORUM_DID); + String stakedTokenMineData = mineIDContentJSON.getString(STAKED_TOKEN); + String stakedTokenSignMineData = mineIDContentJSON.getString(STAKED_TOKEN_SIGN); if (stakerDIDTC.equals(stakerDIDMineData) && stakedTokenTC.equals(stakedTokenMineData) - && stakedTokenSignTC.equals(stakedTokenSignMineData) - && stakerDIDSignTC.equals(stakerDIDSignMineData)) { + && stakedTokenSignTC.equals(stakedTokenSignMineData)) { JSONObject detailsToVerify = new JSONObject(); detailsToVerify.put("did", stakerDIDTC); @@ -527,28 +529,21 @@ public static String receive() { } } - } else if (lastObject.has("mineID")) { + } else if (lastObject.has(MINE_ID)) { - String mineID = lastObject.getString("mineID"); + String mineID = lastObject.getString(MINE_ID); String mineIDContent = get(mineID, ipfs); JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - String stakerDID = mineIDContentJSON.getString("stakerDID"); - String stakerDIDSign = mineIDContentJSON.getString("stakerDIDSignature"); - String stakedToken = mineIDContentJSON.getString("stakedToken"); - String stakedTokenSign = mineIDContentJSON.getString("stakedTokenSignature"); - - JSONObject StakerToVerify = new JSONObject(); - StakerToVerify.put("did", senderDidIpfsHash); - StakerToVerify.put("hash", stakerDID); - StakerToVerify.put("signature", stakerDIDSign); + String stakerDID = mineIDContentJSON.getString(STAKED_QUORUM_DID); + String stakedToken = mineIDContentJSON.getString(STAKED_TOKEN); + String stakedTokenSign = mineIDContentJSON.getString(STAKED_TOKEN_SIGN); JSONObject tokenToVerify = new JSONObject(); tokenToVerify.put("did", senderDidIpfsHash); tokenToVerify.put("hash", stakedToken); tokenToVerify.put("signature", stakedTokenSign); - if (Authenticate.verifySignature(StakerToVerify.toString()) - && Authenticate.verifySignature(tokenToVerify.toString())) { + if (Authenticate.verifySignature(tokenToVerify.toString())) { // ArrayList ownersArray = new ArrayList(); // ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); From 9da2d28d0220d0ff40382b5927461686574e26de Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 31 Mar 2022 14:26:26 +0530 Subject: [PATCH 060/179] stopping staked token Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 50234fb0..83bfd8ac 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -557,6 +557,10 @@ public static String receive() { // ownerCheck = false; // invalidTokens.put(tokens); // } + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); + ownerCheck = false; + invalidTokens.put(tokens); } else { TokenReceiverLogger.debug( From 1fb661ebd0d45fa7159e537b133e2c7d8b455c57 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 31 Mar 2022 16:59:17 +0530 Subject: [PATCH 061/179] fix PC check Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/ProofCredits.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 30201c1f..11878070 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -424,7 +424,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // do { // } while (StakeConsensus.stakeDetails.length() < 6); - if (StakeConsensus.stakeDetails.length() == 6) { + if (StakeConsensus.stakeDetails.length() > 0) { tokenChainArray.put(StakeConsensus.stakeDetails); ProofCreditsLogger.debug("Stake Details for new mined token: " + StakeConsensus.stakeDetails); } else { From cda112bc4358b7658ec7edfef896ea7882b063b3 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 31 Mar 2022 18:00:08 +0530 Subject: [PATCH 062/179] added PC while loop Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/ProofCredits.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 11878070..6ebfb899 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -421,8 +421,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject, ipfs, SEND_PORT + 3, "alpha-stake-token"); - // do { - // } while (StakeConsensus.stakeDetails.length() < 6); + do { + } while (StakeConsensus.stakeDetails.length() < 8); if (StakeConsensus.stakeDetails.length() > 0) { tokenChainArray.put(StakeConsensus.stakeDetails); From 4d9ae4f02519fabe8f1c6612c783fd13095d8c67 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 31 Mar 2022 19:21:02 +0530 Subject: [PATCH 063/179] added sender detail to stake data object in TC Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 4 +++- src/com/rubix/Consensus/StakeConsensus.java | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index e15b211e..2297e1b5 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -2,13 +2,14 @@ import static com.rubix.Constants.ConsensusConstants.INIT_HASH; import static com.rubix.Constants.MiningConstants.MINED_RBT; -import static com.rubix.Constants.MiningConstants.*; +import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; import static com.rubix.Constants.MiningConstants.MINE_ID; import static com.rubix.Constants.MiningConstants.MINE_TID; import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; +import static com.rubix.Constants.MiningConstants.STAKE_DATA; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; @@ -296,6 +297,7 @@ STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + stakingSigns.put( MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", genesisBlock.getString("tokenHash"))); + stakingSigns.put("sender", genesisBlock.getString("sender")); genesisBlock.put(STAKE_DATA, stakingSigns); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index f5378922..585055be 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -242,7 +242,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } do { - } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 4); + } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 7); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); From 742b65067e93d6592d04a0b1e484e2e49e421c83 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 31 Mar 2022 21:49:45 +0530 Subject: [PATCH 064/179] sender data in staking data TC Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 2 +- src/com/rubix/Consensus/StakeConsensus.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 2297e1b5..072aa023 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -297,7 +297,6 @@ STAKED_TOKEN_SIGN, getSignFromShares(DATA_PATH + didHash + stakingSigns.put( MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", genesisBlock.getString("tokenHash"))); - stakingSigns.put("sender", genesisBlock.getString("sender")); genesisBlock.put(STAKE_DATA, stakingSigns); @@ -323,6 +322,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // mine ID stakingSigns.put(MINE_ID, mineID); + stakingSigns.put("sender", genesisBlock.getString("sender")); QuorumConsensusLogger.debug("Token Staked Successfully. MINE ID: " + mineID); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 585055be..1ebbcd57 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -242,7 +242,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } do { - } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 7); + } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); From 9f3da0976a598432b70c43a72fe85157be9d192c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 11:39:16 +0530 Subject: [PATCH 065/179] traverse through multiple tokens to find stake token Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 64 ++++++++++++++------ 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 072aa023..4bcf1f47 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -228,24 +228,51 @@ public void run() { if (bankArray.length() != 0) { - JSONObject bankObject = bankArray.getJSONObject(0); - String stakedTokenHash = bankObject.getString("tokenHash"); - tokenToStake.put(stakedTokenHash); - bankArray.remove(0); - bankArray.put(bankObject); - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); + File tokenFile; + File tokenchainFile; + JSONObject bankObject = new JSONObject(); + String stakedTokenHash = ""; + boolean tokenAvailableToStake = false; + JSONArray stakedTokenChainArray = new JSONArray(); - File tokenFile = new File(TOKENS_PATH + stakedTokenHash); - File tokenchainFile = new File(TOKENCHAIN_PATH + stakedTokenHash + ".json"); + // for loop to check bankArray for token + for (int i = 0; i < bankArray.length(); i++) { - // check if token file and tokenchain file exists - if (tokenFile.exists() && tokenchainFile.exists()) { + bankObject = bankArray.getJSONObject(i); + stakedTokenHash = bankObject.getString("tokenHash"); - QuorumConsensusLogger.debug("Token and TokenChain files found"); + tokenFile = new File(TOKENS_PATH + stakedTokenHash); + tokenchainFile = new File(TOKENCHAIN_PATH + stakedTokenHash + ".json"); + + if (tokenFile.exists() && tokenchainFile.exists()) { + + String tokenChain = readFile(TOKENCHAIN_PATH + stakedTokenHash + ".json"); + stakedTokenChainArray = new JSONArray(tokenChain); + + // get last object of tokenchainarray + JSONObject lastTokenChainObject = stakedTokenChainArray + .getJSONObject(stakedTokenChainArray.length() - 1); + + if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake) { + + QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); + tokenToStake.put(stakedTokenHash); + tokenToStake.put(stakedTokenChainArray); + + bankArray.remove(i); + bankArray.put(bankObject); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); - String tokenChain = readFile(TOKENCHAIN_PATH + stakedTokenHash + ".json"); - JSONArray tokenChainArray = new JSONArray(tokenChain); - tokenToStake.put(tokenChainArray); + tokenAvailableToStake = true; + + break; + } + } + } + + if (tokenAvailableToStake) { + + QuorumConsensusLogger.debug("Token and TokenChain files found"); String hashString = stakedTokenHash.concat(senderDidIpfsHash); String hashForPositions = calculateHash(hashString, "SHA3-256"); @@ -300,10 +327,6 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", genesisBlock.put(STAKE_DATA, stakingSigns); - // stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + - // "/PrivateShare.png", - // mineDetToSign.getString(MINE_ID))); - FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "stake.txt"), true); shareWriter.write(genesisBlock.toString()); @@ -328,8 +351,9 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", mineID); out.println(stakingSigns.toString()); - tokenChainArray.put(stakingSigns); - writeToFile(TOKENCHAIN_PATH + stakedTokenHash + ".json", tokenChainArray.toString(), + stakedTokenChainArray.put(stakingSigns); + writeToFile(TOKENCHAIN_PATH + stakedTokenHash + ".json", + stakedTokenChainArray.toString(), false); QuorumConsensusLogger.debug("Staking Completed!"); From 6445df8f4dc42ad4a9109a71bb1d1db59a99f459 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 12:51:27 +0530 Subject: [PATCH 066/179] quorum response to staking fix Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 19 ++++++++++++------- src/com/rubix/Consensus/StakeConsensus.java | 3 +++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 4bcf1f47..f8b2130e 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -148,7 +148,8 @@ public void run() { QuorumConsensusLogger.debug("Validating new token details: " + genesisBlock); System.out.println(genesisBlock); - boolean isValid = false; + boolean LEVEL_VALID = false; + boolean MINE_CREDIT_VALID = false; // ! check token is in same level String TokenContent = genesisBlock.getString("tokenContent"); @@ -180,7 +181,10 @@ public void run() { if (level_credit == tokenLevelInt) { QuorumConsensusLogger.debug("Validated level of newly minted token"); - isValid = true; + LEVEL_VALID = true; + } else { + QuorumConsensusLogger.debug("Invalid level of newly minted token"); + LEVEL_VALID = false; } } else @@ -204,21 +208,21 @@ public void run() { if (Authenticate.verifySignature(VerificationPick.toString())) { QuorumConsensusLogger.debug("Validated signature of newly minted token"); - isValid = true; + MINE_CREDIT_VALID = true; } else { QuorumConsensusLogger.debug("Signature not verified"); - isValid = false; + MINE_CREDIT_VALID = false; } } catch (Exception e) { QuorumConsensusLogger .debug("Mined Token - Quorum Signature Hash not found. Skipping... Exception: " + e.getMessage()); - // isValid = false; + MINE_CREDIT_VALID = false; } } - if (isValid) { + if (LEVEL_VALID && MINE_CREDIT_VALID) { QuorumConsensusLogger.debug("Sending staking token details..."); JSONArray tokenToStake = new JSONArray(); @@ -253,7 +257,8 @@ public void run() { JSONObject lastTokenChainObject = stakedTokenChainArray .getJSONObject(stakedTokenChainArray.length() - 1); - if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake) { + if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake + && stakedTokenChainArray.length() > tokenLevelValue) { QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); tokenToStake.put(stakedTokenHash); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 1ebbcd57..3a84283d 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -98,6 +98,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } catch (SocketException e) { StakeConsensusLogger .debug("Mined Token Details validation failed. Received null response"); + qOut[j].println("alpha-stake-token-not-verified"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } if (qResponse[j].length() > 3) { @@ -142,11 +143,13 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject ownerCheck = false; StakeConsensusLogger.debug( "Ownership Check Failed for index " + j + " with DID: " + owner); + qOut[j].println("alpha-stake-token-not-verified"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } } else { StakeConsensusLogger.debug("insufficient stake token height details"); + qOut[j].println("alpha-stake-token-not-verified"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } From ef723b0e64f9a7e95195678c0dfbd34de7e0c1d1 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 12:54:08 +0530 Subject: [PATCH 067/179] rm stake token height check for now Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index f8b2130e..aa0b7662 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -257,8 +257,8 @@ public void run() { JSONObject lastTokenChainObject = stakedTokenChainArray .getJSONObject(stakedTokenChainArray.length() - 1); - if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake - && stakedTokenChainArray.length() > tokenLevelValue) { + if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake) { + // && stakedTokenChainArray.length() > tokenLevelValue QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); tokenToStake.put(stakedTokenHash); From c20a0af6808babce1f395ef5e08a3fb6d2919b70 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 14:19:38 +0530 Subject: [PATCH 068/179] fix: fetching tid from genesisBlock Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index aa0b7662..896b0f37 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -146,7 +146,6 @@ public void run() { JSONObject genesisBlock = new JSONObject(response); QuorumConsensusLogger.debug("Validating new token details: " + genesisBlock); - System.out.println(genesisBlock); boolean LEVEL_VALID = false; boolean MINE_CREDIT_VALID = false; @@ -203,7 +202,7 @@ public void run() { JSONObject VerificationPick = new JSONObject(); VerificationPick.put("signature", signature); VerificationPick.put("did", signer); - VerificationPick.put("hash", genesisSignatures.getString("tid")); + VerificationPick.put("hash", genesisBlock.getString("tid")); if (Authenticate.verifySignature(VerificationPick.toString())) { From 27a553e954c7fc876b9774b311fdf2383329a607 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 15:15:28 +0530 Subject: [PATCH 069/179] rm mine credit check for testing Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 896b0f37..c74e4e78 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -204,6 +204,8 @@ public void run() { VerificationPick.put("did", signer); VerificationPick.put("hash", genesisBlock.getString("tid")); + QuorumConsensusLogger.debug("Verifying credit signature of new token: " + VerificationPick); + if (Authenticate.verifySignature(VerificationPick.toString())) { QuorumConsensusLogger.debug("Validated signature of newly minted token"); @@ -221,7 +223,8 @@ public void run() { } - if (LEVEL_VALID && MINE_CREDIT_VALID) { + if (LEVEL_VALID) { + // && MINE_CREDIT_VALID QuorumConsensusLogger.debug("Sending staking token details..."); JSONArray tokenToStake = new JSONArray(); From 3e3bf9f67627d1f71551aae4daa6e674841b7cf9 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 15:39:38 +0530 Subject: [PATCH 070/179] stake failed count Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 3a84283d..9e9a8d0d 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -34,6 +34,7 @@ public class StakeConsensus { private static int socketTimeOut = 1800000; private static volatile boolean STAKE_LOCKED = false; private static volatile boolean STAKE_SUCCESS = false; + private static volatile int STAKE_FAILED = 0; public static volatile JSONObject stakeDetails = new JSONObject(); // MINE_ID // QST_HEIGHT @@ -99,6 +100,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject StakeConsensusLogger .debug("Mined Token Details validation failed. Received null response"); qOut[j].println("alpha-stake-token-not-verified"); + STAKE_FAILED++; IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } if (qResponse[j].length() > 3) { @@ -144,12 +146,14 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject StakeConsensusLogger.debug( "Ownership Check Failed for index " + j + " with DID: " + owner); qOut[j].println("alpha-stake-token-not-verified"); + STAKE_FAILED++; IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } } else { StakeConsensusLogger.debug("insufficient stake token height details"); qOut[j].println("alpha-stake-token-not-verified"); + STAKE_FAILED++; IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } @@ -208,30 +212,37 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } } else { + STAKE_FAILED++; StakeConsensusLogger.debug( "Stake signatures not received.. Quorum response: " + qResponse[j]); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } else { + STAKE_FAILED++; StakeConsensusLogger.debug("Ownership Check Failed"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } } else if (qResponse[j].equals("444")) { + STAKE_FAILED++; StakeConsensusLogger.debug("Quorum could not verify mined token. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("445")) { + STAKE_FAILED++; StakeConsensusLogger.debug("Insufficient quorum member balance. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("446")) { + STAKE_FAILED++; StakeConsensusLogger .debug("Token files picked by quorum to stake is corroupted. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("447")) { + STAKE_FAILED++; StakeConsensusLogger.debug("alpha-stake-token-not-verified. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else { StakeConsensusLogger.debug("Unexpected response from staker: " + qResponse[j]); + STAKE_FAILED++; IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } @@ -244,7 +255,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject quorumThreads[j].start(); } do { - + StakeConsensusLogger.debug("Staking in progress...Rejected by α Quorums: " + STAKE_FAILED + " of 5"); } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8); } catch (Exception e) { From 0eede73bdb6d2c5b53e007d1e544806793a33869 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 15:56:26 +0530 Subject: [PATCH 071/179] exiting staking Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 9e9a8d0d..7b818f6a 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -255,8 +255,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject quorumThreads[j].start(); } do { - StakeConsensusLogger.debug("Staking in progress...Rejected by α Quorums: " + STAKE_FAILED + " of 5"); - } while (!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8); + // StakeConsensusLogger.debug("Staking in progress...Rejected by α Quorums: " + + // STAKE_FAILED + " of 5"); + } while ((!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8) || STAKE_FAILED == 5); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); From 28bb1a6b767d8b538889f954517b0c0a2b957cf8 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 15:58:04 +0530 Subject: [PATCH 072/179] exit condition for staking failed Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- src/com/rubix/Mining/ProofCredits.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 7b818f6a..bf73f9ed 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -34,7 +34,7 @@ public class StakeConsensus { private static int socketTimeOut = 1800000; private static volatile boolean STAKE_LOCKED = false; private static volatile boolean STAKE_SUCCESS = false; - private static volatile int STAKE_FAILED = 0; + public static volatile int STAKE_FAILED = 0; public static volatile JSONObject stakeDetails = new JSONObject(); // MINE_ID // QST_HEIGHT diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 6ebfb899..d78794e4 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -422,7 +422,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON "alpha-stake-token"); do { - } while (StakeConsensus.stakeDetails.length() < 8); + } while (StakeConsensus.stakeDetails.length() < 8 || StakeConsensus.STAKE_FAILED == 5); if (StakeConsensus.stakeDetails.length() > 0) { tokenChainArray.put(StakeConsensus.stakeDetails); From 1ec30c109a804456b23ebad35cf73f9e0ccfc079 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 1 Apr 2022 17:12:38 +0530 Subject: [PATCH 073/179] rm staked token in sender side Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- src/com/rubix/TokenTransfer/TokenReceiver.java | 5 +++-- src/com/rubix/TokenTransfer/TokenSender.java | 4 ++++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index bf73f9ed..4bb3c955 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -257,7 +257,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject do { // StakeConsensusLogger.debug("Staking in progress...Rejected by α Quorums: " + // STAKE_FAILED + " of 5"); - } while ((!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8) || STAKE_FAILED == 5); + } while ((!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8) || STAKE_FAILED < 5); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 83bfd8ac..1087fbf5 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -405,7 +405,7 @@ public static String receive() { JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); TokenReceiverLogger.debug("Last Object = " + lastObject); - if (lastObject.has("owner")) { + if (lastObject.has("senderSign")) { TokenReceiverLogger.debug("Checking ownership"); String owner = lastObject.getString("owner"); @@ -529,7 +529,8 @@ public static String receive() { } } - } else if (lastObject.has(MINE_ID)) { + } + if (lastObject.has(MINE_ID)) { String mineID = lastObject.getString(MINE_ID); String mineIDContent = get(mineID, ipfs); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 3726a96e..db6333ca 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -194,6 +194,10 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String tokenChainFileContent = readFile(TOKENCHAIN_PATH + wholeTokens.get(i) + ".json"); JSONArray tokenChainFileArray = new JSONArray(tokenChainFileContent); JSONArray previousSenderArray = new JSONArray(); + JSONObject lastObject = tokenChainFileArray.getJSONObject(tokenChainFileArray.length() - 1); + if (lastObject.has("mineID")) { + wholeTokens.remove(i); + } for (int j = 0; j < tokenChainFileArray.length(); j++) { String peerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", tokenChainFileArray.getJSONObject(j).getString("sender")); From e27a494d0a8ffac18902a10f01f2ab421fabb844 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 4 Apr 2022 18:33:24 +0530 Subject: [PATCH 074/179] update advisory node endpoints --- src/com/rubix/Consensus/QuorumConsensus.java | 4 ++-- src/com/rubix/Mining/ProofCredits.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index c74e4e78..f9aac359 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -156,7 +156,7 @@ public void run() { int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); - String GET_URL_credit = SYNC_IP + "/getlevel"; + String GET_URL_credit = SYNC_IP + "/getCurentLevel"; URL URLobj_credit = new URL(GET_URL_credit); HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); con_credit.setRequestMethod("GET"); @@ -422,7 +422,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // Get level of token from advisory node int creditsRequired = 0; JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getlevel"; + String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; URL URLobj_credit = new URL(GET_URL_credit); HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); con_credit.setRequestMethod("GET"); diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index d78794e4..b5e16d07 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -104,7 +104,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON QSTHeight = availableCredits + creditsHistoryArray.length(); ProofCreditsLogger.debug("Credits available: " + availableCredits); - String GET_URL_credit = SYNC_IP + "/getlevel"; + String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; URL URLobj_credit = new URL(GET_URL_credit); HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); con_credit.setRequestMethod("GET"); @@ -140,7 +140,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.debug("Credits Old: " + oldCreditsFlag); // String GET_URL = SYNC_IP+"/getInfo?count="+availableCredits; - String GET_URL = SYNC_IP + "/minetoken"; + String GET_URL = SYNC_IP + "/getTokenToMine"; URL URLobj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) URLobj.openConnection(); con.setRequestMethod("GET"); From 9b88c8cd04d82d1ae4b6df30c83553e75a202de9 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 4 Apr 2022 19:53:31 +0530 Subject: [PATCH 075/179] bug fixes --- src/com/rubix/Mining/ProofCredits.java | 9 +++++---- src/com/rubix/TokenTransfer/TokenReceiver.java | 7 ++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index b5e16d07..c9e56741 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -358,10 +358,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // String tkHash = null; for (int i = 0; i < token.length(); i++) { - writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); - String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); - writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); - deleteFile(LOGGER_PATH + "tempToken"); FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); shareWriter.write(InitiatorConsensus.quorumSignature.toString()); @@ -437,6 +433,11 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.warn("Staking failed"); return APIResponse; } + + writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); + String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); + writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); + deleteFile(LOGGER_PATH + "tempToken"); writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 1087fbf5..84a774ca 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -469,10 +469,11 @@ public static String receive() { String tokenLevel = TokenContent.substring(0, 3); int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); - int tokenNumber = 1200001; + int minumumStakeHeight = tokenLevelValue * 4; + int tokenNumber = 1204401; - if (ownerCheck && (tokenChain.length() < tokenLevelValue) && (tokenLevelInt >= 4) - && (tokenNumber > 1200000)) { + if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) + && (tokenNumber > 1204400)) { // ! staking checks (2): For incoming new mint token, verify the staked token From 03e9504a3b8c5545d66cc5982c6539fa807e4473 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 00:26:48 +0530 Subject: [PATCH 076/179] rm tokenAvailableToStake check --- src/com/rubix/Consensus/QuorumConsensus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index f9aac359..06b1ef26 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -259,7 +259,7 @@ public void run() { JSONObject lastTokenChainObject = stakedTokenChainArray .getJSONObject(stakedTokenChainArray.length() - 1); - if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake) { + if (!lastTokenChainObject.has(MINE_ID)) { // && stakedTokenChainArray.length() > tokenLevelValue QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); From 63a52c5bc3e44ce3bd9835e8f2f293572e626530 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Tue, 5 Apr 2022 09:27:33 +0530 Subject: [PATCH 077/179] Included Token Hash --- src/com/rubix/Mining/ProofCredits.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index c9e56741..e0e50c44 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -358,7 +358,12 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // String tkHash = null; for (int i = 0; i < token.length(); i++) { - + + writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); + String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); + writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); + deleteFile(LOGGER_PATH + "tempToken"); + FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); shareWriter.write(InitiatorConsensus.quorumSignature.toString()); shareWriter.close(); @@ -434,11 +439,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON return APIResponse; } - writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); - String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); - writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); - deleteFile(LOGGER_PATH + "tempToken"); - writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); From fae1e347eb9a71c8370fca9ed25f397c87a64e6a Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 11:06:18 +0530 Subject: [PATCH 078/179] rm LEVEL_VALID check --- src/com/rubix/Consensus/QuorumConsensus.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 06b1ef26..9249447b 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -223,8 +223,8 @@ public void run() { } - if (LEVEL_VALID) { - // && MINE_CREDIT_VALID + if (true) { + // LEVEL_VALID && MINE_CREDIT_VALID QuorumConsensusLogger.debug("Sending staking token details..."); JSONArray tokenToStake = new JSONArray(); From e705fd6634eb6bcae68b44e150539c7329c7c201 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 12:22:32 +0530 Subject: [PATCH 079/179] 3/5 staking Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 33 ++--- src/com/rubix/Consensus/StakeConsensus.java | 52 ++++---- src/com/rubix/Mining/ProofCredits.java | 17 +-- .../rubix/TokenTransfer/TokenReceiver.java | 117 ++++++++++++------ 4 files changed, 136 insertions(+), 83 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index c74e4e78..0935e068 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -156,7 +156,7 @@ public void run() { int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); - String GET_URL_credit = SYNC_IP + "/getlevel"; + String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; URL URLobj_credit = new URL(GET_URL_credit); HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); con_credit.setRequestMethod("GET"); @@ -256,23 +256,28 @@ public void run() { stakedTokenChainArray = new JSONArray(tokenChain); // get last object of tokenchainarray - JSONObject lastTokenChainObject = stakedTokenChainArray - .getJSONObject(stakedTokenChainArray.length() - 1); + if (tokenChain.length() > 0) { - if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake) { - // && stakedTokenChainArray.length() > tokenLevelValue + JSONObject lastTokenChainObject = stakedTokenChainArray + .getJSONObject(stakedTokenChainArray.length() - 1); - QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); - tokenToStake.put(stakedTokenHash); - tokenToStake.put(stakedTokenChainArray); + if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake) { + // && stakedTokenChainArray.length() > tokenLevelValue - bankArray.remove(i); - bankArray.put(bankObject); - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); + QuorumConsensusLogger + .debug("Staking 1 RBT for incoming mining transaction..."); + tokenToStake.put(stakedTokenHash); + tokenToStake.put(stakedTokenChainArray); - tokenAvailableToStake = true; + bankArray.remove(i); + bankArray.put(bankObject); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), + false); - break; + tokenAvailableToStake = true; + + break; + } } } } @@ -422,7 +427,7 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // Get level of token from advisory node int creditsRequired = 0; JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getlevel"; + String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; URL URLobj_credit = new URL(GET_URL_credit); HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); con_credit.setRequestMethod("GET"); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 4bb3c955..806d54b9 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -32,10 +32,10 @@ public class StakeConsensus { public static Logger StakeConsensusLogger = Logger.getLogger(StakeConsensus.class); private static int socketTimeOut = 1800000; - private static volatile boolean STAKE_LOCKED = false; - private static volatile boolean STAKE_SUCCESS = false; + private static volatile int STAKE_LOCKED = 0; + private static volatile int STAKE_SUCCESS = 0; public static volatile int STAKE_FAILED = 0; - public static volatile JSONObject stakeDetails = new JSONObject(); + public static volatile JSONArray stakeDetails = new JSONArray(); // MINE_ID // QST_HEIGHT // STAKED_QUORUM_DID @@ -91,6 +91,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject qOut[j].println(operation); if (operation.equals("alpha-stake-token")) { + String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", + quorumPID[j]); + qOut[j].println(data.toString()); StakeConsensusLogger.debug("Mined Token Details sent for validation..."); @@ -108,8 +111,6 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject StakeConsensusLogger .debug("Mined Token Details validated. Received staked token details.."); Boolean ownerCheck = true; - String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", - quorumPID[j]); JSONArray stakeTokenArray = new JSONArray(qResponse[j]); String stakeTokenHash = stakeTokenArray.getString(0); JSONArray stakeTC = stakeTokenArray.getJSONArray(1); @@ -157,9 +158,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } - if (ownerCheck && !STAKE_LOCKED) { + if (ownerCheck && !(STAKE_LOCKED == 3)) { StakeConsensusLogger.debug("Ownership Check Success for Peer: " + quorumPID[j]); - STAKE_LOCKED = true; + STAKE_LOCKED++; StakeConsensusLogger.debug("Staking locked with for Peer: " + quorumPID[j]); qOut[j].println("alpha-stake-token-verified"); StakeConsensusLogger.debug("Waiting for stake signatures"); @@ -179,7 +180,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject if (mineSigns.length() > 0) { - stakeDetails = mineSigns; + // stakeDetails = mineSigns; String quorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", quorumPID[j]); @@ -187,28 +188,30 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject // ! validate signatures StakeConsensusLogger.debug("Validating Signatures"); JSONObject mineIDSign = new JSONObject(); - mineIDSign.put("did", stakeDetails.getString(quorumDID)); - mineIDSign.put("hash", stakeDetails.getString(MINE_ID)); - mineIDSign.put("signature", stakeDetails.getString(MINE_ID_SIGN)); + mineIDSign.put("did", mineSigns.getString(quorumDID)); + mineIDSign.put("hash", mineSigns.getString(MINE_ID)); + mineIDSign.put("signature", mineSigns.getString(MINE_ID_SIGN)); boolean mineSignCheck = Authenticate.verifySignature(mineIDSign.toString()); ArrayList ownersArray = new ArrayList(); ownersArray = IPFSNetwork.dhtOwnerCheck(MINE_ID); if (ownersArray.contains(STAKED_QUORUM_DID)) { - StakeConsensusLogger.debug("Staking pin check passed: " + stakeDetails + StakeConsensusLogger.debug("Staking pin check passed: " + mineSigns .getString(STAKED_QUORUM_DID)); } else { - StakeConsensusLogger.debug("Staking pin check failed: " + stakeDetails + StakeConsensusLogger.debug("Staking pin check failed for DID: " + mineSigns .getString(STAKED_QUORUM_DID)); } if (mineSignCheck) { StakeConsensusLogger.debug( - "########--Staking Complete!--###########"); + "########--Staking Complete " + STAKE_SUCCESS + "/5 !--########"); qOut[j].println("staking-completed"); - STAKE_SUCCESS = true; + StakeConsensusLogger.debug("Staking completed for Peer: " + quorumPID[j]); + stakeDetails.put(mineSigns); + STAKE_SUCCESS++; } } else { @@ -225,23 +228,28 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } else if (qResponse[j].equals("444")) { STAKE_FAILED++; - StakeConsensusLogger.debug("Quorum could not verify mined token. Skipping..."); + StakeConsensusLogger.debug( + "Quorum (DID: " + stakerDID + ") could not verify mined token. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("445")) { STAKE_FAILED++; - StakeConsensusLogger.debug("Insufficient quorum member balance. Skipping..."); + StakeConsensusLogger.debug("Insufficient quorum (DID: " + stakerDID + + ") member balance. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("446")) { STAKE_FAILED++; StakeConsensusLogger - .debug("Token files picked by quorum to stake is corroupted. Skipping..."); + .debug("Token files picked by quorum (DID: " + stakerDID + + ") to stake is corroupted. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("447")) { STAKE_FAILED++; - StakeConsensusLogger.debug("alpha-stake-token-not-verified. Skipping..."); + StakeConsensusLogger.debug("alpha-stake-token-not-verified. (DID: " + stakerDID + + ") Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else { - StakeConsensusLogger.debug("Unexpected response from staker: " + qResponse[j]); + StakeConsensusLogger.debug("Unexpected response from staker (DID: " + stakerDID + + ") : " + qResponse[j]); STAKE_FAILED++; IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } @@ -257,7 +265,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject do { // StakeConsensusLogger.debug("Staking in progress...Rejected by α Quorums: " + // STAKE_FAILED + " of 5"); - } while ((!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8) || STAKE_FAILED < 5); + // } while ((!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8) || + // STAKE_FAILED < 3); + } while ((!(STAKE_SUCCESS == 3) && !(STAKE_LOCKED == 3) && stakeDetails.length() < 8) || STAKE_FAILED < 3); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index d78794e4..5889de0d 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -104,7 +104,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON QSTHeight = availableCredits + creditsHistoryArray.length(); ProofCreditsLogger.debug("Credits available: " + availableCredits); - String GET_URL_credit = SYNC_IP + "/getlevel"; + String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; URL URLobj_credit = new URL(GET_URL_credit); HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); con_credit.setRequestMethod("GET"); @@ -140,7 +140,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.debug("Credits Old: " + oldCreditsFlag); // String GET_URL = SYNC_IP+"/getInfo?count="+availableCredits; - String GET_URL = SYNC_IP + "/minetoken"; + String GET_URL = SYNC_IP + "/getTokenToMine"; URL URLobj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) URLobj.openConnection(); con.setRequestMethod("GET"); @@ -172,7 +172,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON resJsonData.getJSONObject(i).getInt("token"))); creditUsed += (int) Math.pow(2, (2 + resJsonData.getJSONObject(i).getInt("level"))); - } if (resJsonData.getJSONObject(0).getInt("level") == 1) @@ -360,7 +359,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON for (int i = 0; i < token.length(); i++) { writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); - writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); deleteFile(LOGGER_PATH + "tempToken"); FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); @@ -422,10 +420,14 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON "alpha-stake-token"); do { - } while (StakeConsensus.stakeDetails.length() < 8 || StakeConsensus.STAKE_FAILED == 5); + } while (StakeConsensus.stakeDetails.length() < 3 || StakeConsensus.STAKE_FAILED < 3); + + if (StakeConsensus.stakeDetails.length() == 3) { + + for (int j = 0; j < StakeConsensus.stakeDetails.length(); j++) { + tokenChainArray.put(StakeConsensus.stakeDetails.getJSONObject(j)); + } - if (StakeConsensus.stakeDetails.length() > 0) { - tokenChainArray.put(StakeConsensus.stakeDetails); ProofCreditsLogger.debug("Stake Details for new mined token: " + StakeConsensus.stakeDetails); } else { updateQuorum(quorumArray, null, false, type); @@ -438,6 +440,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON return APIResponse; } + writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 1087fbf5..5d00610b 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -469,66 +469,101 @@ public static String receive() { String tokenLevel = TokenContent.substring(0, 3); int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + int minumumStakeHeight = tokenLevelValue * 4; + // TODO: get correct token number from token content int tokenNumber = 1200001; - if (ownerCheck && (tokenChain.length() < tokenLevelValue) && (tokenLevelInt >= 4) - && (tokenNumber > 1200000)) { + if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) + && (tokenNumber > 1204400)) { // ! staking checks (2): For incoming new mint token, verify the staked token - JSONObject secondObject = tokenChain.getJSONObject(1); - String stakedTokenTC = secondObject.getString(STAKED_TOKEN); - String stakedTokenSignTC = secondObject.getString(STAKED_TOKEN_SIGN); - String stakerDIDTC = secondObject.getString(STAKED_QUORUM_DID); - String mineIDTC = secondObject.getString(MINE_ID); - String mineIDSignTC = secondObject.getString(MINE_ID_SIGN); - - String mineIDContent = get(mineIDTC, ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - String stakerDIDMineData = mineIDContentJSON.getString(STAKED_QUORUM_DID); - String stakedTokenMineData = mineIDContentJSON.getString(STAKED_TOKEN); - String stakedTokenSignMineData = mineIDContentJSON.getString(STAKED_TOKEN_SIGN); - - if (stakerDIDTC.equals(stakerDIDMineData) && stakedTokenTC.equals(stakedTokenMineData) - && stakedTokenSignTC.equals(stakedTokenSignMineData)) { - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakerDIDTC); - detailsToVerify.put("hash", mineIDTC); - detailsToVerify.put("signature", mineIDSignTC); - if (Authenticate.verifySignature(detailsToVerify.toString())) { - - ArrayList ownersArray = new ArrayList(); - ownersArray = IPFSNetwork.dhtOwnerCheck(stakedTokenMineData); - - if (ownersArray.contains(stakerDIDTC)) { - TokenReceiverLogger.debug("Staking check passed: " + stakerDIDTC); + JSONObject oneOfThreeStake = tokenChain.getJSONObject(1); + JSONObject twoOfThreeStake = tokenChain.getJSONObject(2); + JSONObject threeOfThreeStake = tokenChain.getJSONObject(3); + + String[] stakedTokenTC = new String[3]; + String[] stakedTokenSignTC = new String[3]; + String[] stakerDIDTC = new String[3]; + String[] mineIDTC = new String[3]; + String[] mineIDSignTC = new String[3]; + + stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); + mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); + mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); + mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); + + for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { + + String mineIDContent = get(mineIDTC[0], ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + String stakerDIDMineData = mineIDContentJSON.getString(STAKED_QUORUM_DID); + String stakedTokenMineData = mineIDContentJSON.getString(STAKED_TOKEN); + String stakedTokenSignMineData = mineIDContentJSON.getString(STAKED_TOKEN_SIGN); + + if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) + && stakedTokenTC[stakeCount].equals(stakedTokenMineData) + && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakerDIDTC); + detailsToVerify.put("hash", mineIDTC); + detailsToVerify.put("signature", mineIDSignTC); + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + ArrayList ownersArray = new ArrayList(); + ownersArray = IPFSNetwork.dhtOwnerCheck(stakedTokenMineData); + + if (ownersArray.contains(stakerDIDTC)) { + TokenReceiverLogger.debug("Staking check passed: " + stakerDIDTC); + } else { + TokenReceiverLogger.debug( + "Staking check (2) failed - staked token " + stakedTokenMineData + + " is not owned by staker: " + + stakerDIDTC); + ownerCheck = false; + invalidTokens.put(tokens); + } + } else { TokenReceiverLogger.debug( - "Staking check (2) failed - staked token " + stakedTokenMineData - + " is not owned by staker: " + "Staking check (2) failed - unable to verify mine ID signature by staker: " + stakerDIDTC); ownerCheck = false; invalidTokens.put(tokens); } - } else { - TokenReceiverLogger.debug( - "Staking check (2) failed - unable to verify mine ID signature by staker: " + TokenReceiverLogger + .debug("MineID Verification Successful with Staking node: " + stakerDIDTC); + } else { + TokenReceiverLogger.debug("Staking check (2) failed"); ownerCheck = false; invalidTokens.put(tokens); } - TokenReceiverLogger - .debug("MineID Verification Successful with Staking node: " + stakerDIDTC); - } else { - TokenReceiverLogger.debug("Staking check (2) failed"); - ownerCheck = false; - invalidTokens.put(tokens); + TokenReceiverLogger.debug("Staking check (2) successful"); + // } else { + // TokenReceiverLogger.debug( + // "Staking check (2) failed: Could not verify mine ID signature"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } } } - } if (lastObject.has(MINE_ID)) { From 7c927512aa4238ec6b3821c653e8450b9909c013 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 13:03:12 +0530 Subject: [PATCH 080/179] rm stake token length requirement Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 29 +++++++------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index d347dbbe..a6c8e953 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -157,7 +157,6 @@ public void run() { int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; - URL URLobj_credit = new URL(GET_URL_credit); HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); con_credit.setRequestMethod("GET"); @@ -257,31 +256,23 @@ public void run() { stakedTokenChainArray = new JSONArray(tokenChain); // get last object of tokenchainarray - if (tokenChain.length() > 0) { + JSONObject lastTokenChainObject = stakedTokenChainArray + .getJSONObject(stakedTokenChainArray.length() - 1); - JSONObject lastTokenChainObject = stakedTokenChainArray - .getJSONObject(stakedTokenChainArray.length() - 1); if (!lastTokenChainObject.has(MINE_ID)) { // && stakedTokenChainArray.length() > tokenLevelValue + QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); + tokenToStake.put(stakedTokenHash); + tokenToStake.put(stakedTokenChainArray); - if (!lastTokenChainObject.has(MINE_ID) && !tokenAvailableToStake) { - // && stakedTokenChainArray.length() > tokenLevelValue - - QuorumConsensusLogger - .debug("Staking 1 RBT for incoming mining transaction..."); - tokenToStake.put(stakedTokenHash); - tokenToStake.put(stakedTokenChainArray); - - bankArray.remove(i); - bankArray.put(bankObject); - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), - false); + bankArray.remove(i); + bankArray.put(bankObject); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); - tokenAvailableToStake = true; + tokenAvailableToStake = true; - break; - } + break; } } } From 63fc11583c9f75434aded1499023bc2c73aca68c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 15:41:16 +0530 Subject: [PATCH 081/179] token receiver fix Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index ac654d72..19594e37 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -405,7 +405,7 @@ public static String receive() { JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); TokenReceiverLogger.debug("Last Object = " + lastObject); - if (lastObject.has("senderSign")) { + if (lastObject.has("owner") && !lastObject.has(MINE_ID)) { TokenReceiverLogger.debug("Checking ownership"); String owner = lastObject.getString("owner"); From c30742b998f8d4c64f13e6e522682e5a6d99fd6a Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 16:12:20 +0530 Subject: [PATCH 082/179] genesis signature check for older tokens Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 19594e37..46abff21 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -458,11 +458,13 @@ public static String receive() { invalidTokens.put(tokens); } - } else { - TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not found"); - ownerCheck = false; - invalidTokens.put(tokens); } + // else { + // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not + // found"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } // ! staking checks (1): Check incoming token level String TokenContent = get(wholeTokens.getString(count), ipfs); From 3bcdae7906f8eb6d79ee60222f1dfcfbb5a09111 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 16:14:03 +0530 Subject: [PATCH 083/179] genesis sign check only for TC with block number Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 46abff21..ef9c1d5f 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -433,7 +433,7 @@ public static String receive() { // ! staking checks (3): Verify the signatures earned during the mining of the // ! incoming mint token JSONObject genesiObject = tokenChain.getJSONObject(0); - if (genesiObject.has("genesisSignatures")) { + if (genesiObject.has("blockNumber")) { int randomNumber = new Random().nextInt(15); String genesisSignaturesContent = genesiObject.getString("quorumSigContent"); From adf9ff60c1c17317c0fffcd90e4e6382e3c2cb20 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 16:33:54 +0530 Subject: [PATCH 084/179] moved genesis token check to level number Signed-off-by: Nidhin Mahesh A --- .../rubix/TokenTransfer/TokenReceiver.java | 43 +++++++++---------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index ef9c1d5f..74102dca 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -430,10 +430,20 @@ public static String receive() { // ! staking checks (1..4) starts here - // ! staking checks (3): Verify the signatures earned during the mining of the - // ! incoming mint token - JSONObject genesiObject = tokenChain.getJSONObject(0); - if (genesiObject.has("blockNumber")) { + // ! staking checks (1): Check incoming token level + String TokenContent = get(wholeTokens.getString(count), ipfs); + String tokenLevel = TokenContent.substring(0, 3); + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + int minumumStakeHeight = tokenLevelValue * 4; + int tokenNumber = 1204401; + + if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) + && (tokenNumber > 1204400)) { + + // ! staking checks (3): Verify the signatures earned during the mining of the + // ! incoming mint token + JSONObject genesiObject = tokenChain.getJSONObject(0); int randomNumber = new Random().nextInt(15); String genesisSignaturesContent = genesiObject.getString("quorumSigContent"); @@ -450,7 +460,6 @@ public static String receive() { ownerCheck = false; invalidTokens.put(tokens); } - } else { TokenReceiverLogger.debug( "Staking check (3) failed: Genesis TID is not equal to the hash of the genesis signature"); @@ -458,24 +467,12 @@ public static String receive() { invalidTokens.put(tokens); } - } - // else { - // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not - // found"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - - // ! staking checks (1): Check incoming token level - String TokenContent = get(wholeTokens.getString(count), ipfs); - String tokenLevel = TokenContent.substring(0, 3); - int tokenLevelInt = Integer.parseInt(tokenLevel); - int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); - int minumumStakeHeight = tokenLevelValue * 4; - int tokenNumber = 1204401; - - if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) - && (tokenNumber > 1204400)) { + // else { + // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not + // found"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } // ! staking checks (2): For incoming new mint token, verify the staked token From d798b5642533a709a84635e36a5e9faee68e200d Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 17:35:01 +0530 Subject: [PATCH 085/179] stake token height check correction Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Ping/QuorumPingReceive.java | 60 ++++++++++++++--- src/com/rubix/Ping/VerifyStakedToken.java | 80 +++++++++++++++++++++++ 2 files changed, 130 insertions(+), 10 deletions(-) create mode 100644 src/com/rubix/Ping/VerifyStakedToken.java diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java index 354315df..6afaa40a 100644 --- a/src/com/rubix/Ping/QuorumPingReceive.java +++ b/src/com/rubix/Ping/QuorumPingReceive.java @@ -1,24 +1,18 @@ package com.rubix.Ping; -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.getPeerID; -import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.Functions.*; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; +import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -58,6 +52,7 @@ public static String receive(int port) throws JSONException { BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintStream output = new PrintStream(sk.getOutputStream()); + int height = 0; String pingRequest; try { pingRequest = input.readLine(); @@ -83,7 +78,52 @@ public static String receive(int port) throws JSONException { APIResponse.put("message", "Pong Sent"); QuorumPingReceiverLogger.info("Pong Sent"); - } else { + } + else if (pingRequest != null && pingRequest.contains("Get-TokenChain-Height")) { + String tokenHash; + try { + tokenHash = input.readLine(); + } catch (SocketException e) { + QuorumPingReceiverLogger.warn("Sender Stream Null - tokenHash"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - tokenHash"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + if (tokenHash != null && tokenHash.startsWith("Qm") && tokenHash.length() == 46) { + QuorumPingReceiverLogger.info("Token chain height requested for: " + tokenHash); + File tokenChainFile = new File(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + if(!tokenChainFile.exists()) { + QuorumPingReceiverLogger.info("Token chain file not found"); + height = 0; + } + else{ + String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + JSONArray chainArray = new JSONArray(tokenChain); + height = chainArray.length()-1; + QuorumPingReceiverLogger.info("Chain height: " + height); + } + } + else{ + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Request Failed"); + QuorumPingReceiverLogger.info("Request Failed"); + } + output.println(height); + + APIResponse.put("status", "Success"); + APIResponse.put("message", "Pong Sent"); + QuorumPingReceiverLogger.info("Pong Sent"); + + } + else { APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong Failed"); QuorumPingReceiverLogger.info("Pong Failed"); diff --git a/src/com/rubix/Ping/VerifyStakedToken.java b/src/com/rubix/Ping/VerifyStakedToken.java new file mode 100644 index 00000000..1d1b5666 --- /dev/null +++ b/src/com/rubix/Ping/VerifyStakedToken.java @@ -0,0 +1,80 @@ +package com.rubix.Ping; + +import io.ipfs.api.IPFS; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.Socket; +import java.net.SocketException; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.IPFSNetwork.*; + +public class VerifyStakedToken { + private static final Logger PingSenderLogger = Logger.getLogger(VerifyStakedToken.class); + public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + + public static boolean Contact(String pid, int port, String token) throws IOException, JSONException { + repo(ipfs); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + JSONObject APIResponse = new JSONObject(); + + String appName = pid.concat("Ping"); + forward(appName, port, pid); + PingSenderLogger.debug("Forwarded to " + appName + " on " + port + " for collecting credits"); + Socket senderSocket = new Socket("127.0.0.1", port); + + BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); + PrintStream output = new PrintStream(senderSocket.getOutputStream()); + + output.println("Get-TokenChain-Height"); + output.println(token); + String heightResponse; + try { + heightResponse = input.readLine(); + } catch (SocketException e) { + PingSenderLogger.warn("Quorum " + pid + " is unable to Respond! - Credits Ping"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pid); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Quorum " + pid + "is unable to respond! - Credits Ping"); + + return false; + } + + + int height = 0; + if (heightResponse == null) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pid); + PingSenderLogger.info("TokenChain height not received"); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "TokenChain height not received"); + + }else { + PingSenderLogger.info("TokenChain height received from " + pid); + PingSenderLogger.info("TokenChain height: " + heightResponse); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pid); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Success"); + APIResponse.put("message", Integer.parseInt(heightResponse)); + height = Integer.parseInt(heightResponse); + + } + + return height >= 46; + } +} \ No newline at end of file From 4630b1ca990774b5b8f39f5af4136caff86cc5a8 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 5 Apr 2022 17:35:24 +0530 Subject: [PATCH 086/179] stake token height ping mined token Signed-off-by: Nidhin Mahesh A --- .../rubix/TokenTransfer/TokenReceiver.java | 45 ++++++++++--------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 74102dca..cf343a14 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -11,6 +11,7 @@ import static com.rubix.Resources.Functions.LOGGER_PATH; import static com.rubix.Resources.Functions.PAYMENTS_PATH; import static com.rubix.Resources.Functions.RECEIVER_PORT; +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; @@ -53,6 +54,7 @@ import com.rubix.AuthenticateNode.Authenticate; import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Ping.VerifyStakedToken; import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; @@ -522,16 +524,18 @@ public static String receive() { detailsToVerify.put("signature", mineIDSignTC); if (Authenticate.verifySignature(detailsToVerify.toString())) { - ArrayList ownersArray = new ArrayList(); - ownersArray = IPFSNetwork.dhtOwnerCheck(stakedTokenMineData); - - if (ownersArray.contains(stakerDIDTC)) { - TokenReceiverLogger.debug("Staking check passed: " + stakerDIDTC); - } else { + boolean minedTokenStatus = true; + ArrayList ownersArray = IPFSNetwork + .dhtOwnerCheck(stakedTokenTC[stakeCount]); + for (int i = 0; i < ownersArray.size(); i++) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + stakedTokenTC[stakeCount])) { + minedTokenStatus = false; + } + } + if (!minedTokenStatus) { TokenReceiverLogger.debug( - "Staking check (2) failed - staked token " + stakedTokenMineData - + " is not owned by staker: " - + stakerDIDTC); + "Staking check failed: Found staked token but token height < 46"); ownerCheck = false; invalidTokens.put(tokens); } @@ -579,18 +583,19 @@ public static String receive() { if (Authenticate.verifySignature(tokenToVerify.toString())) { - // ArrayList ownersArray = new ArrayList(); - // ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + boolean minedTokenStatus = true; + ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + for (int i = 0; i < ownersArray.size(); i++) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, stakedToken)) { + minedTokenStatus = false; + } + } + if (!minedTokenStatus) { + TokenReceiverLogger.debug("Staking check failed: Found staked token but token height < 46"); + ownerCheck = false; + invalidTokens.put(tokens); + } - // if (ownersArray.contains(senderDidIpfsHash)) { - // } else { - // TokenReceiverLogger.debug( - // "Staking check failed - staked token " + stakedToken + " is not owned by - // staker: " - // + senderDidIpfsHash); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } TokenReceiverLogger.debug( "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); ownerCheck = false; From c0480f985fcfcaac188c5cc73542765e269cf283 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 01:04:46 +0530 Subject: [PATCH 087/179] fix mine id sign Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 4 ++++ src/com/rubix/Consensus/StakeConsensus.java | 9 +++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index a6c8e953..8709e124 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -4,6 +4,7 @@ import static com.rubix.Constants.MiningConstants.MINED_RBT; import static com.rubix.Constants.MiningConstants.MINED_RBT_SIGN; import static com.rubix.Constants.MiningConstants.MINE_ID; +import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; import static com.rubix.Constants.MiningConstants.MINE_TID; import static com.rubix.Constants.MiningConstants.MINING_TID_SIGN; import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; @@ -352,6 +353,9 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // mine ID stakingSigns.put(MINE_ID, mineID); + stakingSigns.put(MINE_ID_SIGN, + getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + mineID)); stakingSigns.put("sender", genesisBlock.getString("sender")); QuorumConsensusLogger.debug("Token Staked Successfully. MINE ID: " + diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 806d54b9..56218c65 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -158,10 +158,15 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } - if (ownerCheck && !(STAKE_LOCKED == 3)) { + if (ownerCheck && !(STAKE_LOCKED > 2)) { StakeConsensusLogger.debug("Ownership Check Success for Peer: " + quorumPID[j]); STAKE_LOCKED++; StakeConsensusLogger.debug("Staking locked with for Peer: " + quorumPID[j]); + + // ! wait for all 3 tokens to complete till this step + // ! + // ! + // ! qOut[j].println("alpha-stake-token-verified"); StakeConsensusLogger.debug("Waiting for stake signatures"); @@ -171,7 +176,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .debug("Received stake token signatures: " + qResponse[j]); } catch (SocketException e) { StakeConsensusLogger - .debug("Mined Token Details validation failed. Received null response"); + .debug("Mined Token Details not received from quorum. Received null response"); } // ! add mine signs to tokenchain From 35b2b9929d0f0737963c080047621dfa93de03e4 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 02:21:07 +0530 Subject: [PATCH 088/179] test result merge Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 8 +- src/com/rubix/Consensus/StakeConsensus.java | 115 +++++++++++-------- src/com/rubix/Mining/ProofCredits.java | 37 +++++- 3 files changed, 98 insertions(+), 62 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 8709e124..e1ff0318 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -296,6 +296,7 @@ public void run() { } tokenToStake.put(positions); // ! token which will be staked + out.println("tokenToStake"); out.println(tokenToStake); try { @@ -353,22 +354,19 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // mine ID stakingSigns.put(MINE_ID, mineID); - stakingSigns.put(MINE_ID_SIGN, - getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - mineID)); + stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", mineID)); stakingSigns.put("sender", genesisBlock.getString("sender")); QuorumConsensusLogger.debug("Token Staked Successfully. MINE ID: " + mineID); - out.println(stakingSigns.toString()); stakedTokenChainArray.put(stakingSigns); writeToFile(TOKENCHAIN_PATH + stakedTokenHash + ".json", stakedTokenChainArray.toString(), false); QuorumConsensusLogger.debug("Staking Completed!"); - out.println("200"); + out.println(stakingSigns.toString()); socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 56218c65..85edd546 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -91,26 +91,25 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject qOut[j].println(operation); if (operation.equals("alpha-stake-token")) { - String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", - quorumPID[j]); - qOut[j].println(data.toString()); StakeConsensusLogger.debug("Mined Token Details sent for validation..."); try { qResponse[j] = qIn[j].readLine(); - } catch (SocketException e) { - StakeConsensusLogger - .debug("Mined Token Details validation failed. Received null response"); - qOut[j].println("alpha-stake-token-not-verified"); - STAKE_FAILED++; - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } - if (qResponse[j].length() > 3) { + + if(qResponse[j] !=null && qResponse[j].equals("tokenToStake")) { + + try { + qResponse[j] = qIn[j].readLine(); + + if(qResponse[j] != null) { + /****** start */ StakeConsensusLogger .debug("Mined Token Details validated. Received staked token details.."); Boolean ownerCheck = true; + String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", + quorumPID[j]); JSONArray stakeTokenArray = new JSONArray(qResponse[j]); String stakeTokenHash = stakeTokenArray.getString(0); JSONArray stakeTC = stakeTokenArray.getJSONArray(1); @@ -144,41 +143,36 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject if (!owner.equals(ownerRecalculated)) { ownerCheck = false; + STAKE_FAILED++; StakeConsensusLogger.debug( "Ownership Check Failed for index " + j + " with DID: " + owner); - qOut[j].println("alpha-stake-token-not-verified"); - STAKE_FAILED++; IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } + } } else { + STAKE_FAILED++; StakeConsensusLogger.debug("insufficient stake token height details"); - qOut[j].println("alpha-stake-token-not-verified"); - STAKE_FAILED++; IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } + qOut[j].println("alpha-stake- if (ownerCheck && !(STAKE_LOCKED > 2)) { StakeConsensusLogger.debug("Ownership Check Success for Peer: " + quorumPID[j]); STAKE_LOCKED++; - StakeConsensusLogger.debug("Staking locked with for Peer: " + quorumPID[j]); - - // ! wait for all 3 tokens to complete till this step - // ! - // ! - // ! - qOut[j].println("alpha-stake-token-verified"); + StakeConsensusLogger.debug("Staking locked with for Peer: " + quorumPID[j]);token-verified"); StakeConsensusLogger.debug("Waiting for stake signatures"); try { qResponse[j] = qIn[j].readLine(); StakeConsensusLogger .debug("Received stake token signatures: " + qResponse[j]); - } catch (SocketException e) { - StakeConsensusLogger - .debug("Mined Token Details not received from quorum. Received null response"); - } + if(qResponse[j] != null && qResponse[j].equals("447")) { + STAKE_FAILED++; + StakeConsensusLogger.debug("Token to stake not verified"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + }else if(qResponse[j] != null) { // ! add mine signs to tokenchain StakeConsensusLogger.debug("Adding mine signatures"); JSONObject mineSigns = new JSONObject(qResponse[j]); @@ -225,58 +219,77 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject "Stake signatures not received.. Quorum response: " + qResponse[j]); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } + } + + + } catch (SocketException e) { + StakeConsensusLogger + .debug("Mined Token Details validation failed. Received null response"); + } + } else { STAKE_FAILED++; StakeConsensusLogger.debug("Ownership Check Failed"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } - } else if (qResponse[j].equals("444")) { + /** End */ + } + + }catch(SocketException e) { + StakeConsensusLogger + .debug("Mined Token Details validation failed. Received null response"); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + } + + }else if(qResponse[j] !=null && qResponse[j].equals("446")) { STAKE_FAILED++; - StakeConsensusLogger.debug( - "Quorum (DID: " + stakerDID + ") could not verify mined token. Skipping..."); + StakeConsensusLogger.debug("Token files picked by quorum to stake is corroupted. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } else if (qResponse[j].equals("445")) { + }else if (qResponse[j].equals("445")) { STAKE_FAILED++; - StakeConsensusLogger.debug("Insufficient quorum (DID: " + stakerDID - + ") member balance. Skipping..."); + StakeConsensusLogger.debug("Insufficient quorum member balance. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } else if (qResponse[j].equals("446")) { + }else if (qResponse[j].equals("444")) { STAKE_FAILED++; - StakeConsensusLogger - .debug("Token files picked by quorum (DID: " + stakerDID - + ") to stake is corroupted. Skipping..."); + StakeConsensusLogger.debug("Quorum could not verify mined token. Skipping..."); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } else if (qResponse[j].equals("447")) { + }else { STAKE_FAILED++; - StakeConsensusLogger.debug("alpha-stake-token-not-verified. (DID: " + stakerDID - + ") Skipping..."); + StakeConsensusLogger.debug("Unexpected response from staker: " + qResponse[j]); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } else { - StakeConsensusLogger.debug("Unexpected response from staker (DID: " + stakerDID - + ") : " + qResponse[j]); - STAKE_FAILED++; + } + + } catch (SocketException e) { + StakeConsensusLogger + .debug("Mined Token Details validation failed. Received null response"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } + } } catch (Exception e) { StakeConsensusLogger.error("Error in quorum consensus thread: " + e); } + StakeConsensusLogger.error("*******STAKE_SUCCESS********* "+STAKE_SUCCESS+" **********STAKE_FAILED*********** " + STAKE_FAILED); }); quorumThreads[j].start(); - } + + do { - // StakeConsensusLogger.debug("Staking in progress...Rejected by α Quorums: " + - // STAKE_FAILED + " of 5"); - // } while ((!STAKE_SUCCESS && !STAKE_LOCKED && stakeDetails.length() < 8) || - // STAKE_FAILED < 3); - } while ((!(STAKE_SUCCESS == 3) && !(STAKE_LOCKED == 3) && stakeDetails.length() < 8) || STAKE_FAILED < 3); - - } catch (Exception e) { + } while (!(STAKE_SUCCESS == 3) || STAKE_FAILED < 2); + + } + + + + + }catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); } + + } } diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 0e0d8285..50623128 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -69,6 +69,10 @@ public class ProofCredits { public static JSONObject create(String data, IPFS ipfs) throws IOException, JSONException { + StakeConsensus.STAKE_SUCCESS = 0; + StakeConsensus.STAKE_LOCKED = 0; + StakeConsensus.STAKE_FAILED = 0; + StakeConsensus.stakeDetails = new JSONArray(); repo(ipfs); JSONObject APIResponse = new JSONObject(); JSONObject detailsObject = new JSONObject(data); @@ -160,6 +164,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } else ProofCreditsLogger.debug("GET request not worked"); + ProofCreditsLogger.debug("*************resJsonData.length()**********"+resJsonData.length()); // Check if node can mine token if (resJsonData.length() > 0) { // Calling Mine token function @@ -168,10 +173,14 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON level = resJsonData.getJSONObject(0).getInt("level"); for (int i = 0; i < resJsonData.length(); i++) { + ProofCreditsLogger.debug("*************level**********"+resJsonData.getJSONObject(i).getInt("level")); + ProofCreditsLogger.debug("*************token**********"+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"))); + } if (resJsonData.getJSONObject(0).getInt("level") == 1) @@ -357,8 +366,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // String tkHash = null; for (int i = 0; i < token.length(); i++) { + writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); + writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); deleteFile(LOGGER_PATH + "tempToken"); FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); @@ -415,19 +426,33 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainArray.put(tokenChainGenesisObject); // ! new token will now need a staked token + + + /* + * do { } while (StakeConsensus.stakeDetails.length() < 8 || + * StakeConsensus.STAKE_FAILED == 5); + */ + + + Thread stakingThread = new Thread(() -> { + try { StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, tokenChainGenesisObject, ipfs, SEND_PORT + 3, "alpha-stake-token"); + } catch (JSONException e) { + e.printStackTrace(); + } + }); + stakingThread.start(); - do { - } while (StakeConsensus.stakeDetails.length() < 3 || StakeConsensus.STAKE_FAILED < 3); - if (StakeConsensus.stakeDetails.length() == 3) { + while((StakeConsensus.STAKE_SUCCESS == false && StakeConsensus.STAKE_FAILED < 5)) { - for (int j = 0; j < StakeConsensus.stakeDetails.length(); j++) { - tokenChainArray.put(StakeConsensus.stakeDetails.getJSONObject(j)); } + ProofCreditsLogger.debug(StakeConsensus.STAKE_SUCCESS+ "************" + StakeConsensus.STAKE_FAILED+"******"+StakeConsensus.stakeDetails.length()+"<<<<<<<<<<<<<"+StakeConsensus.stakeDetails.toString()); + if (StakeConsensus.stakeDetails.length() > 0) { + tokenChainArray.put(StakeConsensus.stakeDetails); ProofCreditsLogger.debug("Stake Details for new mined token: " + StakeConsensus.stakeDetails); } else { updateQuorum(quorumArray, null, false, type); @@ -439,7 +464,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.warn("Staking failed"); return APIResponse; } - writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); + writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); From f8fad442e5de91e14c3befb09629b5998dfd1944 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 02:38:29 +0530 Subject: [PATCH 089/179] test code cleanup for 3/5 Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 356 ++++++++++---------- src/com/rubix/Mining/ProofCredits.java | 55 +-- 2 files changed, 214 insertions(+), 197 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 85edd546..7e100a20 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -32,8 +32,8 @@ public class StakeConsensus { public static Logger StakeConsensusLogger = Logger.getLogger(StakeConsensus.class); private static int socketTimeOut = 1800000; - private static volatile int STAKE_LOCKED = 0; - private static volatile int STAKE_SUCCESS = 0; + public static volatile int STAKE_LOCKED = 0; + public static volatile int STAKE_SUCCESS = 0; public static volatile int STAKE_FAILED = 0; public static volatile JSONArray stakeDetails = new JSONArray(); // MINE_ID @@ -96,200 +96,216 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject try { qResponse[j] = qIn[j].readLine(); - - if(qResponse[j] !=null && qResponse[j].equals("tokenToStake")) { - - try { - qResponse[j] = qIn[j].readLine(); - - if(qResponse[j] != null) { - /****** start */ - StakeConsensusLogger - .debug("Mined Token Details validated. Received staked token details.."); - Boolean ownerCheck = true; - String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", - quorumPID[j]); - JSONArray stakeTokenArray = new JSONArray(qResponse[j]); - String stakeTokenHash = stakeTokenArray.getString(0); - JSONArray stakeTC = stakeTokenArray.getJSONArray(1); - String positionsArray = stakeTokenArray.getString(2); - - // ! check ownership of stakeTC from Token Receiver logic - - if (stakeTC.length() > 0 && stakeTokenHash != null && positionsArray != null) { - - JSONObject lastObject = stakeTC.getJSONObject(stakeTC.length() - 1); - StakeConsensusLogger.debug("Last Object = " + lastObject); - if (lastObject.has("owner")) { - StakeConsensusLogger - .debug("Checking ownership of " + stakeTokenHash + " from DID " - + lastObject.getString("owner") + " for positions send: " - + positionsArray); - String owner = lastObject.getString("owner"); - String tokens = stakeTokenHash; - String hashString = tokens.concat(stakerDID); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - String ownerIdentity = hashForPositions.concat(positionsArray); - String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); - - StakeConsensusLogger.debug("Ownership Here Sender Calculation"); - StakeConsensusLogger.debug("tokens: " + tokens); - StakeConsensusLogger.debug("hashString: " + hashString); - StakeConsensusLogger.debug("hashForPositions: " + hashForPositions); - StakeConsensusLogger.debug("p1: " + positionsArray); - StakeConsensusLogger.debug("ownerIdentity: " + ownerIdentity); - StakeConsensusLogger.debug("ownerIdentityHash: " + ownerRecalculated); - - if (!owner.equals(ownerRecalculated)) { - ownerCheck = false; - STAKE_FAILED++; - StakeConsensusLogger.debug( - "Ownership Check Failed for index " + j + " with DID: " + owner); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } - - } - } else { - STAKE_FAILED++; - StakeConsensusLogger.debug("insufficient stake token height details"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } - - qOut[j].println("alpha-stake- - if (ownerCheck && !(STAKE_LOCKED > 2)) { - StakeConsensusLogger.debug("Ownership Check Success for Peer: " + quorumPID[j]); - STAKE_LOCKED++; - StakeConsensusLogger.debug("Staking locked with for Peer: " + quorumPID[j]);token-verified"); - StakeConsensusLogger.debug("Waiting for stake signatures"); + if (qResponse[j] != null && qResponse[j].equals("tokenToStake")) { try { qResponse[j] = qIn[j].readLine(); - StakeConsensusLogger - .debug("Received stake token signatures: " + qResponse[j]); - - if(qResponse[j] != null && qResponse[j].equals("447")) { - STAKE_FAILED++; - StakeConsensusLogger.debug("Token to stake not verified"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - }else if(qResponse[j] != null) { - // ! add mine signs to tokenchain - StakeConsensusLogger.debug("Adding mine signatures"); - JSONObject mineSigns = new JSONObject(qResponse[j]); - - if (mineSigns.length() > 0) { - - // stakeDetails = mineSigns; - - String quorumDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", - quorumPID[j]); - - // ! validate signatures - StakeConsensusLogger.debug("Validating Signatures"); - JSONObject mineIDSign = new JSONObject(); - mineIDSign.put("did", mineSigns.getString(quorumDID)); - mineIDSign.put("hash", mineSigns.getString(MINE_ID)); - mineIDSign.put("signature", mineSigns.getString(MINE_ID_SIGN)); - boolean mineSignCheck = Authenticate.verifySignature(mineIDSign.toString()); - - ArrayList ownersArray = new ArrayList(); - ownersArray = IPFSNetwork.dhtOwnerCheck(MINE_ID); - - if (ownersArray.contains(STAKED_QUORUM_DID)) { - StakeConsensusLogger.debug("Staking pin check passed: " + mineSigns - .getString(STAKED_QUORUM_DID)); - } else { - StakeConsensusLogger.debug("Staking pin check failed for DID: " + mineSigns - .getString(STAKED_QUORUM_DID)); - } - - if (mineSignCheck) { - StakeConsensusLogger.debug( - "########--Staking Complete " + STAKE_SUCCESS + "/5 !--########"); - qOut[j].println("staking-completed"); - StakeConsensusLogger.debug("Staking completed for Peer: " + quorumPID[j]); - stakeDetails.put(mineSigns); - STAKE_SUCCESS++; + if (qResponse[j] != null) { + /****** start */ + + StakeConsensusLogger + .debug("Mined Token Details validated. Received staked token details.."); + Boolean ownerCheck = true; + String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", + "peerid", + quorumPID[j]); + JSONArray stakeTokenArray = new JSONArray(qResponse[j]); + String stakeTokenHash = stakeTokenArray.getString(0); + JSONArray stakeTC = stakeTokenArray.getJSONArray(1); + String positionsArray = stakeTokenArray.getString(2); + + // ! check ownership of stakeTC from Token Receiver logic + + if (stakeTC.length() > 0 && stakeTokenHash != null + && positionsArray != null) { + + JSONObject lastObject = stakeTC.getJSONObject(stakeTC.length() - 1); + StakeConsensusLogger.debug("Last Object = " + lastObject); + if (lastObject.has("owner")) { + StakeConsensusLogger + .debug("Checking ownership of " + stakeTokenHash + + " from DID " + + lastObject.getString("owner") + + " for positions send: " + + positionsArray); + String owner = lastObject.getString("owner"); + String tokens = stakeTokenHash; + String hashString = tokens.concat(stakerDID); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + String ownerIdentity = hashForPositions.concat(positionsArray); + String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + + StakeConsensusLogger.debug("Ownership Here Sender Calculation"); + StakeConsensusLogger.debug("tokens: " + tokens); + StakeConsensusLogger.debug("hashString: " + hashString); + StakeConsensusLogger.debug("hashForPositions: " + hashForPositions); + StakeConsensusLogger.debug("p1: " + positionsArray); + StakeConsensusLogger.debug("ownerIdentity: " + ownerIdentity); + StakeConsensusLogger + .debug("ownerIdentityHash: " + ownerRecalculated); + + if (!owner.equals(ownerRecalculated)) { + ownerCheck = false; + STAKE_FAILED++; + StakeConsensusLogger.debug( + "Ownership Check Failed for index " + j + " with DID: " + + owner); + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + quorumPID[j]); + } + + } + } else { + STAKE_FAILED++; + StakeConsensusLogger.debug("insufficient stake token height details"); + IPFSNetwork + .executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + } + + if (ownerCheck && !(STAKE_LOCKED > 2)) { + StakeConsensusLogger + .debug("Ownership Check Success for Peer: " + quorumPID[j]); + STAKE_LOCKED++; + qOut[j].println("alpha-stake-token-verified"); + StakeConsensusLogger + .debug("Staking locked with for Peer: " + quorumPID[j]); + StakeConsensusLogger.debug("Waiting for stake signatures"); + + try { + qResponse[j] = qIn[j].readLine(); + StakeConsensusLogger + .debug("Received stake token signatures: " + qResponse[j]); + + if (qResponse[j] != null && qResponse[j].equals("447")) { + STAKE_FAILED++; + StakeConsensusLogger.debug("Token to stake not verified"); + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + quorumPID[j]); + } else if (qResponse[j] != null) { + // ! add mine signs to tokenchain + StakeConsensusLogger.debug("Adding mine signatures"); + JSONObject mineSigns = new JSONObject(qResponse[j]); + + if (mineSigns.length() > 0) { + + // stakeDetails = mineSigns; + + String quorumDID = getValues(DATA_PATH + "DataTable.json", + "didHash", "peerid", + quorumPID[j]); + + // ! validate signatures + StakeConsensusLogger.debug("Validating Signatures"); + JSONObject mineIDSign = new JSONObject(); + mineIDSign.put("did", mineSigns.getString(quorumDID)); + mineIDSign.put("hash", mineSigns.getString(MINE_ID)); + mineIDSign.put("signature", + mineSigns.getString(MINE_ID_SIGN)); + boolean mineSignCheck = Authenticate + .verifySignature(mineIDSign.toString()); + + ArrayList ownersArray = new ArrayList(); + ownersArray = IPFSNetwork.dhtOwnerCheck(MINE_ID); + + if (ownersArray.contains(STAKED_QUORUM_DID)) { + StakeConsensusLogger + .debug("Staking pin check passed: " + mineSigns + .getString(STAKED_QUORUM_DID)); + } else { + StakeConsensusLogger.debug( + "Staking pin check failed for DID: " + mineSigns + .getString(STAKED_QUORUM_DID)); + } + + if (mineSignCheck) { + StakeConsensusLogger.debug( + "########--Staking Complete " + STAKE_SUCCESS + + "/5 !--########"); + + qOut[j].println("staking-completed"); + StakeConsensusLogger.debug( + "Staking completed for Peer: " + quorumPID[j]); + stakeDetails.put(mineSigns); + STAKE_SUCCESS++; + } + + } else { + STAKE_FAILED++; + StakeConsensusLogger.debug( + "Stake signatures not received.. Quorum response: " + + qResponse[j]); + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + quorumPID[j]); + } + } + + } catch (SocketException e) { + StakeConsensusLogger + .debug("Mined Token Details validation failed. Received null response"); + } + + } else { + STAKE_FAILED++; + StakeConsensusLogger.debug("Ownership Check Failed"); + IPFSNetwork + .executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + } + + /** End */ } - } else { - STAKE_FAILED++; - StakeConsensusLogger.debug( - "Stake signatures not received.. Quorum response: " + qResponse[j]); + } catch (SocketException e) { + StakeConsensusLogger + .debug("Mined Token Details validation failed. Received null response"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } - } - - - } catch (SocketException e) { - StakeConsensusLogger - .debug("Mined Token Details validation failed. Received null response"); - } - + + } else if (qResponse[j] != null && qResponse[j].equals("446")) { + STAKE_FAILED++; + StakeConsensusLogger + .debug("Token files picked by quorum to stake is corroupted. Skipping..."); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + } else if (qResponse[j].equals("445")) { + STAKE_FAILED++; + StakeConsensusLogger.debug("Insufficient quorum member balance. Skipping..."); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); + } else if (qResponse[j].equals("444")) { + STAKE_FAILED++; + StakeConsensusLogger.debug("Quorum could not verify mined token. Skipping..."); + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else { STAKE_FAILED++; - StakeConsensusLogger.debug("Ownership Check Failed"); + StakeConsensusLogger.debug("Unexpected response from staker: " + qResponse[j]); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } - /** End */ - } - - }catch(SocketException e) { - StakeConsensusLogger - .debug("Mined Token Details validation failed. Received null response"); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } - - }else if(qResponse[j] !=null && qResponse[j].equals("446")) { - STAKE_FAILED++; - StakeConsensusLogger.debug("Token files picked by quorum to stake is corroupted. Skipping..."); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - }else if (qResponse[j].equals("445")) { - STAKE_FAILED++; - StakeConsensusLogger.debug("Insufficient quorum member balance. Skipping..."); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - }else if (qResponse[j].equals("444")) { - STAKE_FAILED++; - StakeConsensusLogger.debug("Quorum could not verify mined token. Skipping..."); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - }else { - STAKE_FAILED++; - StakeConsensusLogger.debug("Unexpected response from staker: " + qResponse[j]); - IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); - } - - } catch (SocketException e) { - StakeConsensusLogger - .debug("Mined Token Details validation failed. Received null response"); + } catch (SocketException e) { + StakeConsensusLogger + .debug("Mined Token Details validation failed. Received null response"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } - } } catch (Exception e) { StakeConsensusLogger.error("Error in quorum consensus thread: " + e); } - StakeConsensusLogger.error("*******STAKE_SUCCESS********* "+STAKE_SUCCESS+" **********STAKE_FAILED*********** " + STAKE_FAILED); + StakeConsensusLogger.error("*******STAKE_SUCCESS********* " + STAKE_SUCCESS + + " **********STAKE_FAILED*********** " + STAKE_FAILED); }); quorumThreads[j].start(); - - - do { - } while (!(STAKE_SUCCESS == 3) || STAKE_FAILED < 2); - - } - - - - - }catch (Exception e) { + + do { + } while (!(STAKE_SUCCESS == 3) || STAKE_FAILED < 2); + + } + + } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); } - - + } } diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 50623128..8f596e60 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -69,10 +69,10 @@ public class ProofCredits { public static JSONObject create(String data, IPFS ipfs) throws IOException, JSONException { - StakeConsensus.STAKE_SUCCESS = 0; - StakeConsensus.STAKE_LOCKED = 0; - StakeConsensus.STAKE_FAILED = 0; - StakeConsensus.stakeDetails = new JSONArray(); + StakeConsensus.STAKE_SUCCESS = 0; + StakeConsensus.STAKE_LOCKED = 0; + StakeConsensus.STAKE_FAILED = 0; + StakeConsensus.stakeDetails = new JSONArray(); repo(ipfs); JSONObject APIResponse = new JSONObject(); JSONObject detailsObject = new JSONObject(data); @@ -164,7 +164,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } else ProofCreditsLogger.debug("GET request not worked"); - ProofCreditsLogger.debug("*************resJsonData.length()**********"+resJsonData.length()); + ProofCreditsLogger.debug("*************resJsonData.length()**********" + resJsonData.length()); // Check if node can mine token if (resJsonData.length() > 0) { // Calling Mine token function @@ -173,9 +173,11 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON level = resJsonData.getJSONObject(0).getInt("level"); for (int i = 0; i < resJsonData.length(); i++) { - ProofCreditsLogger.debug("*************level**********"+resJsonData.getJSONObject(i).getInt("level")); - ProofCreditsLogger.debug("*************token**********"+resJsonData.getJSONObject(i).getInt("token")); - + ProofCreditsLogger + .debug("*************level**********" + resJsonData.getJSONObject(i).getInt("level")); + ProofCreditsLogger + .debug("*************token**********" + resJsonData.getJSONObject(i).getInt("token")); + token.put(Functions.mineToken(resJsonData.getJSONObject(i).getInt("level"), resJsonData.getJSONObject(i).getInt("token"))); @@ -366,10 +368,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // String tkHash = null; for (int i = 0; i < token.length(); i++) { - + writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); - writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); + writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); deleteFile(LOGGER_PATH + "tempToken"); FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); @@ -426,31 +428,30 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainArray.put(tokenChainGenesisObject); // ! new token will now need a staked token - - - /* - * do { } while (StakeConsensus.stakeDetails.length() < 8 || - * StakeConsensus.STAKE_FAILED == 5); - */ - - + + /* + * do { } while (StakeConsensus.stakeDetails.length() < 8 || + * StakeConsensus.STAKE_FAILED == 5); + */ + Thread stakingThread = new Thread(() -> { try { - StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, - tokenChainGenesisObject, ipfs, SEND_PORT + 3, - "alpha-stake-token"); - } catch (JSONException e) { + StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, + tokenChainGenesisObject, ipfs, SEND_PORT + 3, + "alpha-stake-token"); + } catch (Exception e) { e.printStackTrace(); } }); stakingThread.start(); + while ((StakeConsensus.STAKE_SUCCESS < 2 && StakeConsensus.STAKE_FAILED < 3)) { - while((StakeConsensus.STAKE_SUCCESS == false && StakeConsensus.STAKE_FAILED < 5)) { - - } + } - ProofCreditsLogger.debug(StakeConsensus.STAKE_SUCCESS+ "************" + StakeConsensus.STAKE_FAILED+"******"+StakeConsensus.stakeDetails.length()+"<<<<<<<<<<<<<"+StakeConsensus.stakeDetails.toString()); + ProofCreditsLogger.debug(StakeConsensus.STAKE_SUCCESS + "************" + StakeConsensus.STAKE_FAILED + + "******" + StakeConsensus.stakeDetails.length() + "<<<<<<<<<<<<<" + + StakeConsensus.stakeDetails.toString()); if (StakeConsensus.stakeDetails.length() > 0) { tokenChainArray.put(StakeConsensus.stakeDetails); ProofCreditsLogger.debug("Stake Details for new mined token: " + StakeConsensus.stakeDetails); @@ -464,7 +465,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.warn("Staking failed"); return APIResponse; } - + writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); From 1a7ca43d52387407594d1cf1def0686d2702d49d Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 03:00:57 +0530 Subject: [PATCH 090/179] fix: org.json.JSONException: JSONObject["QmcNLiFF6eWJssko9GY7Rm4NMyrbcoos3WsP5E7QX6Xjo3"] not found. Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 7e100a20..e2d20492 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -199,7 +199,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject // ! validate signatures StakeConsensusLogger.debug("Validating Signatures"); JSONObject mineIDSign = new JSONObject(); - mineIDSign.put("did", mineSigns.getString(quorumDID)); + mineIDSign.put("did", quorumDID); mineIDSign.put("hash", mineSigns.getString(MINE_ID)); mineIDSign.put("signature", mineSigns.getString(MINE_ID_SIGN)); From 09f45415d5edafe2696874a57dbdd85bd5bf7c8a Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 03:16:35 +0530 Subject: [PATCH 091/179] fix while check in stake consensus thread Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index e2d20492..877f632f 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -292,13 +292,13 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } catch (Exception e) { StakeConsensusLogger.error("Error in quorum consensus thread: " + e); } - StakeConsensusLogger.error("*******STAKE_SUCCESS********* " + STAKE_SUCCESS + StakeConsensusLogger.debug("*******STAKE_SUCCESS********* " + STAKE_SUCCESS + " **********STAKE_FAILED*********** " + STAKE_FAILED); }); quorumThreads[j].start(); do { - } while (!(STAKE_SUCCESS == 3) || STAKE_FAILED < 2); + } while (!(STAKE_SUCCESS < 2) || STAKE_FAILED < 3); } From be23428623cc91c0aca90eeec3a56ec9f516e52c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 03:26:34 +0530 Subject: [PATCH 092/179] fix 2/2: while check in stake consensus Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 877f632f..e3a999ff 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -298,7 +298,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject quorumThreads[j].start(); do { - } while (!(STAKE_SUCCESS < 2) || STAKE_FAILED < 3); + } while (STAKE_SUCCESS < 2 || STAKE_FAILED < 3); } From 1dff2f5f466fedcccf1636f0b7b20743ab360b6c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 04:27:33 +0530 Subject: [PATCH 093/179] do while outside forloop Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index e3a999ff..7b93185e 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -297,11 +297,14 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject }); quorumThreads[j].start(); - do { - } while (STAKE_SUCCESS < 2 || STAKE_FAILED < 3); + // do { + // } while (STAKE_SUCCESS < 2 || STAKE_FAILED < 3); } + do { + } while (STAKE_SUCCESS < 2 || STAKE_FAILED < 3); + } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); } From 47dc0c355346c7ac6144f89b7d74082d9826e93c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 04:41:53 +0530 Subject: [PATCH 094/179] DID in stakeConsensus logs Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 40 ++++++++++++++------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 7b93185e..fc027f19 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -92,7 +92,12 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject if (operation.equals("alpha-stake-token")) { qOut[j].println(data.toString()); - StakeConsensusLogger.debug("Mined Token Details sent for validation..."); + + String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", + "peerid", + quorumPID[j]); + + StakeConsensusLogger.debug("Mined Token Details sent for validation...DID: " + stakerDID); try { qResponse[j] = qIn[j].readLine(); @@ -106,11 +111,10 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject /****** start */ StakeConsensusLogger - .debug("Mined Token Details validated. Received staked token details.."); + .debug("Mined Token Details validated. Received staked token details from DID: " + + stakerDID); Boolean ownerCheck = true; - String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", - "peerid", - quorumPID[j]); + JSONArray stakeTokenArray = new JSONArray(qResponse[j]); String stakeTokenHash = stakeTokenArray.getString(0); JSONArray stakeTC = stakeTokenArray.getJSONArray(1); @@ -159,7 +163,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } } else { STAKE_FAILED++; - StakeConsensusLogger.debug("insufficient stake token height details"); + StakeConsensusLogger + .debug("insufficient stake token height details from DID: " + + stakerDID); IPFSNetwork .executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } @@ -197,7 +203,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject quorumPID[j]); // ! validate signatures - StakeConsensusLogger.debug("Validating Signatures"); + StakeConsensusLogger + .debug("Validating Signatures from DID: " + + stakerDID); JSONObject mineIDSign = new JSONObject(); mineIDSign.put("did", quorumDID); mineIDSign.put("hash", mineSigns.getString(MINE_ID)); @@ -234,7 +242,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } else { STAKE_FAILED++; StakeConsensusLogger.debug( - "Stake signatures not received.. Quorum response: " + "Stake signatures not received from DID: " + + stakerDID + " Quorum response: " + qResponse[j]); IPFSNetwork.executeIPFSCommands( "ipfs p2p close -t /p2p/" + quorumPID[j]); @@ -243,7 +252,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } catch (SocketException e) { StakeConsensusLogger - .debug("Mined Token Details validation failed. Received null response"); + .debug("Mined Token Details validation failed for DID: " + + stakerDID + " Received null response"); } } else { @@ -265,15 +275,18 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } else if (qResponse[j] != null && qResponse[j].equals("446")) { STAKE_FAILED++; StakeConsensusLogger - .debug("Token files picked by quorum to stake is corroupted. Skipping..."); + .debug("Token files picked by quorum to stake is corroupted. Skipping...DID: " + + stakerDID); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("445")) { STAKE_FAILED++; - StakeConsensusLogger.debug("Insufficient quorum member balance. Skipping..."); + StakeConsensusLogger.debug("Insufficient quorum member balance. Skipping...DID: " + + stakerDID); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("444")) { STAKE_FAILED++; - StakeConsensusLogger.debug("Quorum could not verify mined token. Skipping..."); + StakeConsensusLogger.debug("Quorum could not verify mined token. Skipping...DID: " + + stakerDID); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else { STAKE_FAILED++; @@ -283,7 +296,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } catch (SocketException e) { StakeConsensusLogger - .debug("Mined Token Details validation failed. Received null response"); + .debug("Mined Token Details validation failed for DID: " + stakerDID + + " Received null response"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } From 58ad1e0cefc57a604fd3ce50e143d1ce6308fac3 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 04:51:00 +0530 Subject: [PATCH 095/179] quorum check token in log Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/QuorumConsensus.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index e1ff0318..9c4b5d4f 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -224,7 +224,7 @@ public void run() { } - if (true) { + if (LEVEL_VALID) { // LEVEL_VALID && MINE_CREDIT_VALID QuorumConsensusLogger.debug("Sending staking token details..."); @@ -233,7 +233,7 @@ public void run() { String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); JSONArray bankArray = new JSONArray(bankFile); - if (bankArray.length() != 0) { + if (bankArray.length() > 0) { File tokenFile; File tokenchainFile; @@ -251,6 +251,8 @@ public void run() { tokenFile = new File(TOKENS_PATH + stakedTokenHash); tokenchainFile = new File(TOKENCHAIN_PATH + stakedTokenHash + ".json"); + QuorumConsensusLogger.debug("Checking token" + stakedTokenHash + " for staking..."); + if (tokenFile.exists() && tokenchainFile.exists()) { String tokenChain = readFile(TOKENCHAIN_PATH + stakedTokenHash + ".json"); @@ -354,7 +356,8 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", // mine ID stakingSigns.put(MINE_ID, mineID); - stakingSigns.put(MINE_ID_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", mineID)); + stakingSigns.put(MINE_ID_SIGN, + getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", mineID)); stakingSigns.put("sender", genesisBlock.getString("sender")); QuorumConsensusLogger.debug("Token Staked Successfully. MINE ID: " + From 0ec30883bb1fe378bb08f720c7b4be9a9bf01495 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 05:14:26 +0530 Subject: [PATCH 096/179] check new token from genesis obj Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index cf343a14..901c6b81 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -405,6 +405,7 @@ public static String receive() { String tokens = null; JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); + JSONObject firstTCObject = tokenChain.getJSONObject(0); TokenReceiverLogger.debug("Last Object = " + lastObject); if (lastObject.has("owner") && !lastObject.has(MINE_ID)) { @@ -438,10 +439,11 @@ public static String receive() { int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); int minumumStakeHeight = tokenLevelValue * 4; - int tokenNumber = 1204401; + int tokenNumber = 1204400; if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) - && (tokenNumber > 1204400)) { + && firstTCObject.has("QSTHeight")) { + // && (tokenNumber > 1204400) // ! staking checks (3): Verify the signatures earned during the mining of the // ! incoming mint token From c4b8eb9ed043c13fcd57f92dec087b19c3fe333c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 6 Apr 2022 15:39:09 +0530 Subject: [PATCH 097/179] 4x level height check in staked token transfer Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Ping/VerifyStakedToken.java | 60 ++++++++++++++++++----- 1 file changed, 49 insertions(+), 11 deletions(-) diff --git a/src/com/rubix/Ping/VerifyStakedToken.java b/src/com/rubix/Ping/VerifyStakedToken.java index 1d1b5666..d5c31713 100644 --- a/src/com/rubix/Ping/VerifyStakedToken.java +++ b/src/com/rubix/Ping/VerifyStakedToken.java @@ -1,20 +1,27 @@ package com.rubix.Ping; -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.IPFS_PORT; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.SYNC_IP; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.forward; +import static com.rubix.Resources.IPFSNetwork.repo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; +import java.net.HttpURLConnection; import java.net.Socket; import java.net.SocketException; +import java.net.URL; -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.*; +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 VerifyStakedToken { private static final Logger PingSenderLogger = Logger.getLogger(VerifyStakedToken.class); @@ -51,7 +58,6 @@ public static boolean Contact(String pid, int port, String token) throws IOExcep return false; } - int height = 0; if (heightResponse == null) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + pid); @@ -62,7 +68,7 @@ public static boolean Contact(String pid, int port, String token) throws IOExcep APIResponse.put("status", "Failed"); APIResponse.put("message", "TokenChain height not received"); - }else { + } else { PingSenderLogger.info("TokenChain height received from " + pid); PingSenderLogger.info("TokenChain height: " + heightResponse); executeIPFSCommands(" ipfs p2p close -t /p2p/" + pid); @@ -72,9 +78,41 @@ public static boolean Contact(String pid, int port, String token) throws IOExcep APIResponse.put("status", "Success"); APIResponse.put("message", Integer.parseInt(heightResponse)); height = Integer.parseInt(heightResponse); - } - return height >= 46; + String tokenLevel = token.substring(0, 3); + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + int requiredMinedTokenHeight = tokenLevelValue * 4; + + String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; + URL URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + // QuorumConsensusLogger.debug("response from service " + + // response_credit.toString()); + JSONObject resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + + // ! release staked token if the mined token is from previous level(s) + if (level_credit > tokenLevelInt) { + return true; + } + + } else + PingSenderLogger.debug("GET request not worked"); + + return height > requiredMinedTokenHeight; } } \ No newline at end of file From 7d313885c476c3213f88a0dc34133e13653617a2 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 8 Apr 2022 17:23:29 +0530 Subject: [PATCH 098/179] ping check with initHash() Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Ping/PingCheck.java | 4 ++-- src/com/rubix/Ping/PingReceive.java | 5 +++-- src/com/rubix/Resources/Functions.java | 31 +++++++++++++------------- 3 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index 87e0a2cb..6500636d 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -3,7 +3,7 @@ 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.*; import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.forward; @@ -82,7 +82,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE return APIResponse; } - if (pongResponse != null && (!pongResponse.equals("Pong"))) { + if (pongResponse != null && (!pongResponse.equals(initHash()))) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); PingSenderLogger.info("Pong response not received"); output.close(); diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index de4a0cf0..966f5234 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -4,6 +4,7 @@ import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; import static com.rubix.Resources.Functions.getPeerID; +import static com.rubix.Resources.Functions.initHash; import static com.rubix.Resources.Functions.pathSet; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; @@ -77,10 +78,10 @@ public static String receive(int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println("Pong"); + output.println(initHash()); APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent"); + APIResponse.put("message", "Pong Sent to Sender with Check Sum"); PingReceiverLogger.info("Pong Sent"); } else { diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index e84a33a6..4391456b 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1512,41 +1512,42 @@ public static void backgroundChecks() { public static String sanityMessage; public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOException, JSONException { - FunctionsLogger.info("Entering SanityCheck"); + FunctionsLogger.info("Entering Receiver SanityCheck"); boolean sanityCheckErrorFlag = true; if (sanityCheckErrorFlag && checkIPFSStatus(peerid, ipfs)) { - FunctionsLogger.debug("IPFS is working in " + peerid); - FunctionsLogger.debug("IPFS check true"); + FunctionsLogger.debug("Receiver IPFS is working in " + peerid); + FunctionsLogger.debug("Receiver IPFS check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("IPFS is not working in " + peerid); - FunctionsLogger.debug("IPFS check false"); - sanityMessage = "IPFS is not working in " + peerid; + FunctionsLogger.debug("Receiver IPFS is not working in " + peerid); + FunctionsLogger.debug("Receiver IPFS check false"); + sanityMessage = "Receiver IPFS is not working in " + peerid; } if (sanityCheckErrorFlag) { if (bootstrapConnect(peerid, ipfs)) { - FunctionsLogger.debug("Bootstrap connected for " + peerid); + FunctionsLogger.debug("Bootstrap connected for Receiver " + peerid); FunctionsLogger.debug("Bootstrap check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Bootstrap connection unsuccessful for " + peerid); + FunctionsLogger.debug("Bootstrap connection unsuccessful for Receiver " + peerid); FunctionsLogger.debug("Bootstrap check false"); - sanityMessage = "Bootstrap connection unsuccessful for " + peerid; + sanityMessage = "Bootstrap connection unsuccessful for Receiver " + peerid; } } - + if (sanityCheckErrorFlag) { if (ping(peerid, port)) { - FunctionsLogger.debug("Jar is running as expected in " + peerid); - FunctionsLogger.debug("Jar check true"); + FunctionsLogger.debug("Rceiver is running the latest Jar " + peerid); + FunctionsLogger.debug("Latest Jar check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Jar is not running in " + peerid); - FunctionsLogger.debug("Jar check false"); - sanityMessage = "Jar is not running in " + peerid; + FunctionsLogger.debug("Receiver is not running the latest Jar " + peerid); + FunctionsLogger.debug("Latest Jar check false"); + sanityMessage = "Receiver is not running the latest Jar. PID: " + peerid; } } + if (sanityCheckErrorFlag) { if (portCheckAndKill(port)) { FunctionsLogger.debug("Ports are available for transcations in " + peerid); From 14bb0700a4d3f8e9ce2d29b7699ab8d8706371dc Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 8 Apr 2022 18:13:55 +0530 Subject: [PATCH 099/179] /getQuorum check before getting token hash Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/ProofCredits.java | 38 ++++++++++---------- src/com/rubix/Resources/Functions.java | 37 +++++++++++-------- src/com/rubix/TokenTransfer/TokenSender.java | 2 +- 3 files changed, 42 insertions(+), 35 deletions(-) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 8f596e60..85b5aa0d 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -143,6 +143,25 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.debug("Credits Old: " + oldCreditsFlag); + JSONArray quorumArray; + switch (type) { + case 2: { + quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + break; + } + default: { + quorumArray = getQuorum(DID, DID, 1); + if (quorumArray.length() == 1) { + APIResponse.put("did", DID); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Type 1 mining not allowed. Please use subnet quorum to mine."); + ProofCreditsLogger.warn("Quorum Members not available for type 1 mining"); + return APIResponse; + } + } + } + // String GET_URL = SYNC_IP+"/getInfo?count="+availableCredits; String GET_URL = SYNC_IP + "/getTokenToMine"; URL URLobj = new URL(GET_URL); @@ -194,25 +213,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON String authSenderByRecHash = calculateHash(token + DID + comments, "SHA3-256"); String tid = calculateHash(authSenderByRecHash, "SHA3-256"); - writeToFile(LOGGER_PATH + "tempbeta", tid.concat(DID), false); - String betaHash = IPFSNetwork.add(LOGGER_PATH + "tempbeta", ipfs); - deleteFile(LOGGER_PATH + "tempbeta"); - - writeToFile(LOGGER_PATH + "tempgamma", tid.concat(DID), false); - String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); - deleteFile(LOGGER_PATH + "tempgamma"); - - JSONArray quorumArray; - switch (type) { - case 2: { - quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); - break; - } - default: { - quorumArray = getQuorum(betaHash, gammaHash, DID, DID, token.length()); - } - } - QuorumSwarmConnect(quorumArray, ipfs); alphaSize = quorumArray.length() - 14; diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 4391456b..eb9a808e 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1022,7 +1022,7 @@ public static void updateQuorum(JSONArray quorumArray, JSONArray signedQuorumLis * @return JSONArray of quorum nodes */ - public static JSONArray getQuorum(String betaHash, String gammaHash, String senderDidIpfsHash, + public static JSONArray getQuorum(String senderDidIpfsHash, String receiverDidIpfsHash, int tokenslength) throws IOException, JSONException { JSONArray quorumArray; String urlQuorumPick = ADVISORY_IP + "/getQuorum"; @@ -1036,8 +1036,7 @@ public static JSONArray getQuorum(String betaHash, String gammaHash, String send conQuorumPick.setRequestProperty("Authorization", "null"); JSONObject dataToSendQuorumPick = new JSONObject(); - dataToSendQuorumPick.put("betahash", betaHash); - dataToSendQuorumPick.put("gammahash", gammaHash); + dataToSendQuorumPick.put("sender", senderDidIpfsHash); dataToSendQuorumPick.put("receiver", receiverDidIpfsHash); dataToSendQuorumPick.put("tokencount", tokenslength); @@ -1054,17 +1053,25 @@ public static JSONArray getQuorum(String betaHash, String gammaHash, String send FunctionsLogger.debug("Post Data : " + populateQuorumPick); FunctionsLogger.debug("Response Code : " + responseCodeQuorumPick); - BufferedReader inQuorumPick = new BufferedReader( - new InputStreamReader(conQuorumPick.getInputStream())); - String outputQuorumPick; - StringBuffer responseQuorumPick = new StringBuffer(); - while ((outputQuorumPick = inQuorumPick.readLine()) != null) { - responseQuorumPick.append(outputQuorumPick); + if (responseCodeQuorumPick == 200) { + + BufferedReader inQuorumPick = new BufferedReader( + new InputStreamReader(conQuorumPick.getInputStream())); + String outputQuorumPick; + StringBuffer responseQuorumPick = new StringBuffer(); + while ((outputQuorumPick = inQuorumPick.readLine()) != null) { + responseQuorumPick.append(outputQuorumPick); + } + inQuorumPick.close(); + FunctionsLogger.debug(" responsequorumpick " + responseQuorumPick.toString()); + quorumArray = new JSONArray(responseQuorumPick.toString()); + return quorumArray; + + } else { + quorumArray = new JSONArray(); + quorumArray.put(false); + return quorumArray; } - inQuorumPick.close(); - FunctionsLogger.debug(" responsequorumpick " + responseQuorumPick.toString()); - quorumArray = new JSONArray(responseQuorumPick.toString()); - return quorumArray; } /** @@ -1535,7 +1542,7 @@ public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOE sanityMessage = "Bootstrap connection unsuccessful for Receiver " + peerid; } } - + if (sanityCheckErrorFlag) { if (ping(peerid, port)) { FunctionsLogger.debug("Rceiver is running the latest Jar " + peerid); @@ -1547,7 +1554,7 @@ public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOE sanityMessage = "Receiver is not running the latest Jar. PID: " + peerid; } } - + if (sanityCheckErrorFlag) { if (portCheckAndKill(port)) { FunctionsLogger.debug("Ports are available for transcations in " + peerid); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index db6333ca..f2956031 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -402,7 +402,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); deleteFile(LOGGER_PATH + "tempgamma"); - quorumArray = getQuorum(betaHash, gammaHash, senderDidIpfsHash, receiverDidIpfsHash, + quorumArray = getQuorum(senderDidIpfsHash, receiverDidIpfsHash, allTokens.length()); break; } From e738a59bb81d0ad4f2f4d39618765fe5c7554b9a Mon Sep 17 00:00:00 2001 From: Gokul P S <94040889+gklps@users.noreply.github.com> Date: Sun, 10 Apr 2022 12:42:49 +0530 Subject: [PATCH 100/179] Updated Windows Sanity Check --- src/com/rubix/Resources/Functions.java | 66 ++++++++++++++++---------- 1 file changed, 41 insertions(+), 25 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index eb9a808e..b3901bd4 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1703,12 +1703,12 @@ public static boolean bootstrapConnect(String peerid, IPFS ipfs) { public static boolean portCheckAndKill(int port) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); boolean portStatus = false; - + long pid = ProcessHandle.current().pid(); + FunctionsLogger.info("Current OS is "+getOsName()); try { - if (getOsName() != "Windows") { + if (!getOsName().toLowerCase().contains("windows")) { portStatus = releasePorts(port); } else { - portStatusWindows(port); portStatus = portStatusWindows(port); } } catch (Exception e) { @@ -1717,7 +1717,6 @@ public static boolean portCheckAndKill(int port) { return portStatus; } - /** * This function will release the port in linux based machines if the port is * already in use @@ -1765,35 +1764,52 @@ public static boolean releasePorts(int port) { public static boolean portStatusWindows(int port) { FunctionsLogger.info("Starting portStatusWindows"); boolean releasedPort = false; - String processStr; + String portProcessStr; Process p; + ArrayList pidTree = new ArrayList(); + ArrayList portPidTree = new ArrayList(); try { Runtime rt = Runtime.getRuntime(); - Process proc = rt.exec("cmd /c netstat -ano | findstr " + port); - FunctionsLogger.info("Checking port status"); - long currentPid = ProcessHandle.current().pid(); - BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); - processStr = stdInput.readLine(); - FunctionsLogger.info("Process id found for port is " + processStr + " current jar pid is " + currentPid); - if (processStr != null && String.valueOf(currentPid) != processStr) { - int index = processStr.lastIndexOf(" "); - String sc = processStr.substring(index, processStr.length()); - // System.out.println("Port "+port+" is locked by PID "+sc+". Kindly close this - // port and retry transcation"); - if (sc != String.valueOf(currentPid)) { - FunctionsLogger.debug("Port " + port + " is locked by PID " + sc); - } else { - FunctionsLogger.debug("Port " + port + " is locked by current jar with PID " + sc); + Process getJarPid = rt.exec("cmd /c netstat -ano | findstr 1898"); + BufferedReader getJarPidBR = new BufferedReader(new InputStreamReader(getJarPid.getInputStream())); + String getJarPidline; + while ((getJarPidline = getJarPidBR.readLine()) != null) { + String[] getJarPidTree = getJarPidline.split("\\s+"); + int temp=Integer.parseInt(getJarPidTree[getJarPidTree.length-1]); + pidTree.add(temp); } - } else { + + FunctionsLogger.info("PIDs occupied by Rubix.jar are " + pidTree); + + Set pidSet = new LinkedHashSet(pidTree); + FunctionsLogger.info("Pid occupied by port 1898 is pidSet"+pidSet); + Process getPortPid = rt.exec("cmd /c netstat -ano | findstr "+ port); + BufferedReader getPortPidBr = new BufferedReader(new InputStreamReader(getPortPid.getInputStream())); + String getPortPidLine; + while((getPortPidLine = getPortPidBr.readLine())!=null){ + String[] getPortPidTree = getPortPidLine.split("\\s+"); + int temp=Integer.parseInt(getPortPidTree[getPortPidTree.length-1]); + portPidTree.add(temp); + } + + Set pidToKill = new LinkedHashSet(portPidTree); + FunctionsLogger.info("Pid used by port "+ port +"is "+ pidToKill); + pidToKill.removeAll(pidSet); + pidToKill.remove(0); + FunctionsLogger.info("Pid using port "+ port +" but not in 1898"+pidToKill); + if(pidToKill.size()>0){ + System.out.println("Port "+port+" is occupied by PIDs"+pidToKill); + } + else { releasedPort = true; - FunctionsLogger.info("Port is unlocked"); } + + } catch (Exception e) { - FunctionsLogger.error("Exception occured at portStatusWindows", e); - e.printStackTrace(); + FunctionsLogger.error("Exception occured at portStatusWindows", e); } return releasedPort; - } + +} } From 24d82b7e6e64bd5cb5ebf4a10b8226682848b03c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 11 Apr 2022 12:04:12 +0530 Subject: [PATCH 101/179] fix quorum sign content fetch error Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Resources/Functions.java | 51 ++++++++++--------- .../rubix/TokenTransfer/TokenReceiver.java | 4 +- 2 files changed, 27 insertions(+), 28 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index b3901bd4..93ea2850 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -32,6 +32,8 @@ import java.util.ArrayList; import java.util.Date; import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; import javax.imageio.ImageIO; @@ -1704,7 +1706,7 @@ public static boolean portCheckAndKill(int port) { PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); boolean portStatus = false; long pid = ProcessHandle.current().pid(); - FunctionsLogger.info("Current OS is "+getOsName()); + FunctionsLogger.info("Current OS is " + getOsName()); try { if (!getOsName().toLowerCase().contains("windows")) { portStatus = releasePorts(port); @@ -1717,6 +1719,7 @@ public static boolean portCheckAndKill(int port) { return portStatus; } + /** * This function will release the port in linux based machines if the port is * already in use @@ -1773,43 +1776,41 @@ public static boolean portStatusWindows(int port) { Process getJarPid = rt.exec("cmd /c netstat -ano | findstr 1898"); BufferedReader getJarPidBR = new BufferedReader(new InputStreamReader(getJarPid.getInputStream())); String getJarPidline; - while ((getJarPidline = getJarPidBR.readLine()) != null) { - String[] getJarPidTree = getJarPidline.split("\\s+"); - int temp=Integer.parseInt(getJarPidTree[getJarPidTree.length-1]); - pidTree.add(temp); - } - - FunctionsLogger.info("PIDs occupied by Rubix.jar are " + pidTree); - + while ((getJarPidline = getJarPidBR.readLine()) != null) { + String[] getJarPidTree = getJarPidline.split("\\s+"); + int temp = Integer.parseInt(getJarPidTree[getJarPidTree.length - 1]); + pidTree.add(temp); + } + + FunctionsLogger.info("PIDs occupied by Rubix.jar are " + pidTree); + Set pidSet = new LinkedHashSet(pidTree); - FunctionsLogger.info("Pid occupied by port 1898 is pidSet"+pidSet); - Process getPortPid = rt.exec("cmd /c netstat -ano | findstr "+ port); + FunctionsLogger.info("Pid occupied by port 1898 is pidSet" + pidSet); + Process getPortPid = rt.exec("cmd /c netstat -ano | findstr " + port); BufferedReader getPortPidBr = new BufferedReader(new InputStreamReader(getPortPid.getInputStream())); String getPortPidLine; - while((getPortPidLine = getPortPidBr.readLine())!=null){ + while ((getPortPidLine = getPortPidBr.readLine()) != null) { String[] getPortPidTree = getPortPidLine.split("\\s+"); - int temp=Integer.parseInt(getPortPidTree[getPortPidTree.length-1]); - portPidTree.add(temp); + int temp = Integer.parseInt(getPortPidTree[getPortPidTree.length - 1]); + portPidTree.add(temp); } - + Set pidToKill = new LinkedHashSet(portPidTree); - FunctionsLogger.info("Pid used by port "+ port +"is "+ pidToKill); + FunctionsLogger.info("Pid used by port " + port + "is " + pidToKill); pidToKill.removeAll(pidSet); pidToKill.remove(0); - FunctionsLogger.info("Pid using port "+ port +" but not in 1898"+pidToKill); - if(pidToKill.size()>0){ - System.out.println("Port "+port+" is occupied by PIDs"+pidToKill); - } - else { + FunctionsLogger.info("Pid using port " + port + " but not in 1898" + pidToKill); + if (pidToKill.size() > 0) { + System.out.println("Port " + port + " is occupied by PIDs" + pidToKill); + } else { releasedPort = true; } - - + } catch (Exception e) { - FunctionsLogger.error("Exception occured at portStatusWindows", e); + FunctionsLogger.error("Exception occured at portStatusWindows", e); } return releasedPort; -} + } } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 901c6b81..c75c8fc3 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -450,9 +450,7 @@ public static String receive() { JSONObject genesiObject = tokenChain.getJSONObject(0); int randomNumber = new Random().nextInt(15); - String genesisSignaturesContent = genesiObject.getString("quorumSigContent"); - // String genesisSignaturesContent = get(genesisSignatures, ipfs); - JSONArray genesisSignaturesContentJSON = new JSONArray(genesisSignaturesContent); + JSONArray genesisSignaturesContentJSON = genesiObject.getJSONArray("quorumSigContent"); JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); if (VerificationPick.getString("hash") == genesiObject.getString("tid")) { From 10fc568f058f8c00e9c0bc48c826fdf7bcd1e530 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 12 Apr 2022 13:29:30 +0530 Subject: [PATCH 102/179] staking update Signed-off-by: Nidhin Mahesh A --- .../rubix/AuthenticateNode/Authenticate.java | 5 +- .../rubix/Consensus/InitiatorProcedure.java | 3 + src/com/rubix/Consensus/QuorumConsensus.java | 528 +++++++++--------- src/com/rubix/Consensus/StakeConsensus.java | 15 +- src/com/rubix/Constants/MiningConstants.java | 1 + src/com/rubix/Mining/ProofCredits.java | 36 +- .../rubix/TokenTransfer/TokenReceiver.java | 83 +-- src/com/rubix/TokenTransfer/TokenSender.java | 21 +- 8 files changed, 371 insertions(+), 321 deletions(-) diff --git a/src/com/rubix/AuthenticateNode/Authenticate.java b/src/com/rubix/AuthenticateNode/Authenticate.java index 866cc40b..8f985043 100644 --- a/src/com/rubix/AuthenticateNode/Authenticate.java +++ b/src/com/rubix/AuthenticateNode/Authenticate.java @@ -62,9 +62,9 @@ public static boolean verifySignature(String detailString) throws IOException, J JSONObject P = randomPositions("verifier", hash, 32, SenderSign); int[] posForSign = (int[]) P.get("posForSign"); int[] originalPos = (int[]) P.get("originalPos"); - for (int positionsLevelTwoTrail : posForSign) + for (int positionsLevelTwoTrail : posForSign) { senderWalletID.append(walletID.charAt(positionsLevelTwoTrail)); - + } String recombinedResult = PropImage.getpos(senderWalletID.toString(), signature); int[] positionsLevelZero = new int[32]; @@ -74,6 +74,7 @@ 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())) { return true; } else { diff --git a/src/com/rubix/Consensus/InitiatorProcedure.java b/src/com/rubix/Consensus/InitiatorProcedure.java index 0a2cc5b9..10557faf 100644 --- a/src/com/rubix/Consensus/InitiatorProcedure.java +++ b/src/com/rubix/Consensus/InitiatorProcedure.java @@ -102,6 +102,9 @@ public static void consensusSetUp(String data, IPFS ipfs, int PORT, int alphaSiz JSONObject dataSend = new JSONObject(); dataSend.put("hash", authQuorumHash); dataSend.put("details", detailsForQuorum); + + InitiatorProcedureLogger.debug("hash"+authQuorumHash); + InitiatorProcedureLogger.debug("data1"+data1.toString()); if (operation.equals("new-credits-mining")) { JSONObject qstDetails = dataObject.getJSONObject("qstDetails"); diff --git a/src/com/rubix/Consensus/QuorumConsensus.java b/src/com/rubix/Consensus/QuorumConsensus.java index 9c4b5d4f..524a92d2 100644 --- a/src/com/rubix/Consensus/QuorumConsensus.java +++ b/src/com/rubix/Consensus/QuorumConsensus.java @@ -127,10 +127,130 @@ public void run() { serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } + // ? staking logic starts here + if (operation.equals("new-credits-mining")) { + QuorumConsensusLogger.debug("New Credits"); + String getNewCreditsData = null; + try { + getNewCreditsData = in.readLine(); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - New Credits Details"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + // Verify QST Credits + JSONObject qstObject = new JSONObject(getNewCreditsData); + + if (qstObject.getString(INIT_HASH).equals(initHash())) { + + // Get level of token from advisory node + int creditsRequired = 0; + JSONObject resJsonData_credit = new JSONObject(); + String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; + URL URLobj_credit = new URL(GET_URL_credit); + HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); + con_credit.setRequestMethod("GET"); + int responseCode_credit = con_credit.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode_credit); + if (responseCode_credit == HttpURLConnection.HTTP_OK) { + BufferedReader in_credit = new BufferedReader( + new InputStreamReader(con_credit.getInputStream())); + String inputLine_credit; + StringBuffer response_credit = new StringBuffer(); + while ((inputLine_credit = in_credit.readLine()) != null) { + response_credit.append(inputLine_credit); + } + in_credit.close(); + // QuorumConsensusLogger.debug("response from service " + + // response_credit.toString()); + resJsonData_credit = new JSONObject(response_credit.toString()); + int level_credit = resJsonData_credit.getInt("level"); + creditsRequired = (int) Math.pow(2, (2 + level_credit)); + QuorumConsensusLogger.debug("credits required " + creditsRequired); + + } else + QuorumConsensusLogger.debug("GET request not worked"); + + // Level 1 Verification: Verify hash of n objects + JSONArray qstArray = qstObject.getJSONArray("qstArray"); + JSONArray creditsArray = qstObject.getJSONArray("credits"); + + boolean flag = true; + // if qstArray has any duplicate object + for (int i = 0; i < qstArray.length(); i++) { + for (int j = i + 1; j < qstArray.length(); j++) { + if (qstArray.getJSONObject(i).getString("credits") + .equals(qstArray.getJSONObject(j).getString("credits"))) { + flag = false; + break; + } + } + } + for (int i = 0; i < creditsRequired; i++) { + QuorumConsensusLogger.debug("Credit object: " + creditsArray.getJSONObject(i).toString()); + QuorumConsensusLogger.debug( + "Credit Hash: " + + calculateHash(creditsArray.getJSONObject(i).toString(), "SHA3-256")); + String reHash = calculateHash(qstArray.getJSONObject(i).getString("credits"), "SHA3-256"); + if (!reHash.equals(qstArray.getJSONObject(i).getString("creditHash"))) { + QuorumConsensusLogger.debug("Recalculation " + reHash + " - " + + qstArray.getJSONObject(i).getString("creditHash")); + flag = false; + } + } - if (operation.equals("alpha-stake-token")) { + if (flag) { + boolean verifySigns = true; + for (int i = 0; i < creditsRequired; i++) { + if (!Authenticate.verifySignature(creditsArray.getJSONObject(i).toString())) + verifySigns = false; + } + if (verifySigns) { + HashSet hashSet = new HashSet(); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < creditsArray.length(); i++) { + String sign = creditsArray.getJSONObject(i).getString("signature"); + String signHash = calculateHash(sign, "SHA3-256"); + hashSet.add(signHash); + } + long endTime = System.currentTimeMillis(); + QuorumConsensusLogger.debug("Total Time for HashSet: " + (endTime - startTime)); + if (hashSet.size() == qstArray.length() * 15) { + QuorumConsensusLogger.debug("Mining Verified"); + out.println("Verified"); + + } else { + QuorumConsensusLogger + .debug("HashSet: " + hashSet.size() + " QST Size " + qstArray.length()); + QuorumConsensusLogger.debug("Mining Not Verified: Duplicates Found"); + out.println("440"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + } else { + out.println("441"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + } else { + out.println("442"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + } else { + out.println("443"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + } + else if (operation.equals("alpha-stake-token")) { QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); String response = null; @@ -257,26 +377,32 @@ public void run() { String tokenChain = readFile(TOKENCHAIN_PATH + stakedTokenHash + ".json"); stakedTokenChainArray = new JSONArray(tokenChain); - - // get last object of tokenchainarray - JSONObject lastTokenChainObject = stakedTokenChainArray - .getJSONObject(stakedTokenChainArray.length() - 1); - - if (!lastTokenChainObject.has(MINE_ID)) { - // && stakedTokenChainArray.length() > tokenLevelValue - - QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); - tokenToStake.put(stakedTokenHash); - tokenToStake.put(stakedTokenChainArray); - - bankArray.remove(i); - bankArray.put(bankObject); - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); - - tokenAvailableToStake = true; - - break; - } + + if(stakedTokenChainArray.length() > 0) { + // get last object of tokenchainarray + JSONObject lastTokenChainObject = stakedTokenChainArray + .getJSONObject(stakedTokenChainArray.length() - 1); + + if (!lastTokenChainObject.has(MINE_ID)) { + // && stakedTokenChainArray.length() > tokenLevelValue + + QuorumConsensusLogger.debug("Staking 1 RBT for incoming mining transaction..."); + tokenToStake.put(stakedTokenHash); + tokenToStake.put(stakedTokenChainArray); + + bankArray.remove(i); + bankArray.put(bankObject); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); + + tokenAvailableToStake = true; + + break; + } + + } else { + + QuorumConsensusLogger.debug("Token Chain does not have enough height to pledge...Trying to pledge with another token!"); + } } } @@ -368,8 +494,10 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", stakedTokenChainArray.toString(), false); - QuorumConsensusLogger.debug("Staking Completed!"); + out.println(stakingSigns.toString()); + QuorumConsensusLogger.debug("Staking Completed!"); + socket.close(); serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); @@ -404,245 +532,127 @@ MINED_RBT_SIGN, getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", serverSocket.close(); executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); } - } - - // ? staking logic ends here - - if (operation.equals("new-credits-mining")) { - QuorumConsensusLogger.debug("New Credits"); - String getNewCreditsData = null; - try { - getNewCreditsData = in.readLine(); - } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - New Credits Details"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - // Verify QST Credits - JSONObject qstObject = new JSONObject(getNewCreditsData); - - if (qstObject.getString(INIT_HASH).equals(initHash())) { - - // Get level of token from advisory node - int creditsRequired = 0; - JSONObject resJsonData_credit = new JSONObject(); - String GET_URL_credit = SYNC_IP + "/getCurrentLevel"; - URL URLobj_credit = new URL(GET_URL_credit); - HttpURLConnection con_credit = (HttpURLConnection) URLobj_credit.openConnection(); - con_credit.setRequestMethod("GET"); - int responseCode_credit = con_credit.getResponseCode(); - System.out.println("GET Response Code :: " + responseCode_credit); - if (responseCode_credit == HttpURLConnection.HTTP_OK) { - BufferedReader in_credit = new BufferedReader( - new InputStreamReader(con_credit.getInputStream())); - String inputLine_credit; - StringBuffer response_credit = new StringBuffer(); - while ((inputLine_credit = in_credit.readLine()) != null) { - response_credit.append(inputLine_credit); - } - in_credit.close(); - // QuorumConsensusLogger.debug("response from service " + - // response_credit.toString()); - resJsonData_credit = new JSONObject(response_credit.toString()); - int level_credit = resJsonData_credit.getInt("level"); - creditsRequired = (int) Math.pow(2, (2 + level_credit)); - QuorumConsensusLogger.debug("credits required " + creditsRequired); - - } else - QuorumConsensusLogger.debug("GET request not worked"); - - // Level 1 Verification: Verify hash of n objects - JSONArray qstArray = qstObject.getJSONArray("qstArray"); - JSONArray creditsArray = qstObject.getJSONArray("credits"); - - boolean flag = true; - // if qstArray has any duplicate object - for (int i = 0; i < qstArray.length(); i++) { - for (int j = i + 1; j < qstArray.length(); j++) { - if (qstArray.getJSONObject(i).getString("credits") - .equals(qstArray.getJSONObject(j).getString("credits"))) { - flag = false; - break; - } - } - } - for (int i = 0; i < creditsRequired; i++) { - QuorumConsensusLogger.debug("Credit object: " + creditsArray.getJSONObject(i).toString()); - QuorumConsensusLogger.debug( - "Credit Hash: " - + calculateHash(creditsArray.getJSONObject(i).toString(), "SHA3-256")); - String reHash = calculateHash(qstArray.getJSONObject(i).getString("credits"), "SHA3-256"); - if (!reHash.equals(qstArray.getJSONObject(i).getString("creditHash"))) { - QuorumConsensusLogger.debug("Recalculation " + reHash + " - " - + qstArray.getJSONObject(i).getString("creditHash")); - flag = false; - } - } - - if (flag) { - boolean verifySigns = true; - for (int i = 0; i < creditsRequired; i++) { - if (!Authenticate.verifySignature(creditsArray.getJSONObject(i).toString())) - verifySigns = false; - } - if (verifySigns) { - HashSet hashSet = new HashSet(); - long startTime = System.currentTimeMillis(); - for (int i = 0; i < creditsArray.length(); i++) { - String sign = creditsArray.getJSONObject(i).getString("signature"); - String signHash = calculateHash(sign, "SHA3-256"); - hashSet.add(signHash); - } - long endTime = System.currentTimeMillis(); - QuorumConsensusLogger.debug("Total Time for HashSet: " + (endTime - startTime)); - if (hashSet.size() == qstArray.length() * 15) { - QuorumConsensusLogger.debug("Mining Verified"); - out.println("Verified"); - } else { - QuorumConsensusLogger - .debug("HashSet: " + hashSet.size() + " QST Size " + qstArray.length()); - QuorumConsensusLogger.debug("Mining Not Verified: Duplicates Found"); - out.println("440"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - } else { - out.println("441"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - } else { - out.println("442"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - } else { - out.println("443"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - } else + } + else QuorumConsensusLogger.debug("Old Credits Mining / Whole RBT Token Transfer"); - String getRecData = null; - try { - getRecData = in.readLine(); - } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - Ping Check / Receiver Details"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - - if (getRecData != null) { - if (getRecData.contains("ping check")) { - QuorumConsensusLogger.debug("Ping check from sender: " + getRecData); - out.println("pong response"); - } else { - - QuorumConsensusLogger.debug("Received Details from initiator: " + getRecData); - readSenderData = new JSONObject(getRecData); - senderPrivatePos = readSenderData.getString("sign"); - senderDidIpfsHash = readSenderData.getString("senderDID"); - transactionID = readSenderData.getString("Tid"); - verifySenderHash = readSenderData.getString("Hash"); - receiverDID = readSenderData.getString("RID"); - // initHash = readSenderData.getString(INIT_HASH); - - 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"); - - QuorumConsensusLogger.debug("1: " + verifySenderHash); - QuorumConsensusLogger.debug("2: " + receiverDID); - QuorumConsensusLogger.debug("Quorum hash: " + quorumHash); - - 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"); - - if (Authenticate.verifySignature(detailsToVerify.toString())) { - QuorumConsensusLogger.debug("Quorum Authenticated Sender"); - - QuorumConsensusLogger.debug("ConsensusID pass"); - String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", - quorumHash); - out.println(QuorumSignature); - - String creditSignatures = null; - try { - creditSignatures = in.readLine(); - } catch (SocketException e) { - QuorumConsensusLogger.debug("Sender Input Stream Null - Credits"); - socket.close(); - serverSocket.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); - } - QuorumConsensusLogger.debug("credit Signature " + creditSignatures); - - if (!creditSignatures.equals("null")) { // commented as per test for multiple consensus - // threads - FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); - shareWriter.write(creditSignatures); - shareWriter.close(); - File readCredit = new File(LOGGER_PATH + "mycredit.txt"); - String credit = add(readCredit.toString(), ipfs); - - File creditFile = new File( - WALLET_DATA_PATH.concat("/Credits/").concat(credit).concat(".json")); - if (!creditFile.exists()) - creditFile.createNewFile(); - writeToFile(creditFile.toString(), creditSignatures, false); - - QuorumConsensusLogger.debug("Credit object: " + credit); - QuorumConsensusLogger.debug("Credit Hash: " + calculateHash(credit, "SHA3-256")); - JSONObject storeDetailsQuorum = new JSONObject(); - storeDetailsQuorum.put("tid", transactionID); - storeDetailsQuorum.put("consensusID", verifySenderHash); - storeDetailsQuorum.put("sign", senderPrivatePos); - storeDetailsQuorum.put("credits", credit); - storeDetailsQuorum.put("creditHash", calculateHash(credit, "SHA3-256")); - storeDetailsQuorum.put("senderdid", senderDidIpfsHash); - storeDetailsQuorum.put("Date", Functions.getCurrentUtcTime()); - 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 - Quorum"); - out.println("Auth_Failed"); - } - - } - } else { - QuorumConsensusLogger.debug("Quorum - " + didHash + " is unable to respond!" + getRecData); - out.println(getRecData); - } - + String getRecData = null; + try { + getRecData = in.readLine(); + + if (getRecData != null) { + if (getRecData.contains("ping check")) { + QuorumConsensusLogger.debug("Ping check from sender: " + getRecData); + out.println("pong response"); + } else { + + QuorumConsensusLogger.debug("Received Details from initiator: " + getRecData); + readSenderData = new JSONObject(getRecData); + senderPrivatePos = readSenderData.getString("sign"); + senderDidIpfsHash = readSenderData.getString("senderDID"); + transactionID = readSenderData.getString("Tid"); + verifySenderHash = readSenderData.getString("Hash"); + receiverDID = readSenderData.getString("RID"); + // initHash = readSenderData.getString(INIT_HASH); + + 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"); + + QuorumConsensusLogger.debug("1: " + senderPrivatePos); + QuorumConsensusLogger.debug("2: " + senderDidIpfsHash); + QuorumConsensusLogger.debug("3: " + transactionID); + QuorumConsensusLogger.debug("4: " + verifySenderHash); + + 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"); + + if (Authenticate.verifySignature(detailsToVerify.toString())) { + QuorumConsensusLogger.debug("Quorum Authenticated Sender"); + + QuorumConsensusLogger.debug("ConsensusID pass"); + String QuorumSignature = getSignFromShares(DATA_PATH + didHash + "/PrivateShare.png", + quorumHash); + + QuorumConsensusLogger.debug(QuorumSignature); + out.println(QuorumSignature); + + String creditSignatures = null; + try { + creditSignatures = in.readLine(); + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - Credits"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + QuorumConsensusLogger.debug("credit Signature " + creditSignatures); + + if (!creditSignatures.equals("null")) { // commented as per test for multiple consensus + // threads + FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); + shareWriter.write(creditSignatures); + shareWriter.close(); + File readCredit = new File(LOGGER_PATH + "mycredit.txt"); + String credit = add(readCredit.toString(), ipfs); + + File creditFile = new File( + WALLET_DATA_PATH.concat("/Credits/").concat(credit).concat(".json")); + if (!creditFile.exists()) + creditFile.createNewFile(); + writeToFile(creditFile.toString(), creditSignatures, false); + + QuorumConsensusLogger.debug("Credit object: " + credit); + QuorumConsensusLogger.debug("Credit Hash: " + calculateHash(credit, "SHA3-256")); + JSONObject storeDetailsQuorum = new JSONObject(); + storeDetailsQuorum.put("tid", transactionID); + storeDetailsQuorum.put("consensusID", verifySenderHash); + storeDetailsQuorum.put("sign", senderPrivatePos); + storeDetailsQuorum.put("credits", credit); + storeDetailsQuorum.put("creditHash", calculateHash(credit, "SHA3-256")); + storeDetailsQuorum.put("senderdid", senderDidIpfsHash); + storeDetailsQuorum.put("Date", Functions.getCurrentUtcTime()); + 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 - Quorum"); + out.println("Auth_Failed"); + } + + } + } else { + QuorumConsensusLogger.debug("Quorum - " + didHash + " is unable to respond!" + getRecData); + out.println(getRecData); + } + } catch (SocketException e) { + QuorumConsensusLogger.debug("Sender Input Stream Null - Ping Check / Receiver Details"); + socket.close(); + serverSocket.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + } + } catch (IOException e) { QuorumConsensusLogger.error("IOException Occurred", e); } catch (JSONException e) { diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index fc027f19..8d70bcfb 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -211,8 +211,10 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject mineIDSign.put("hash", mineSigns.getString(MINE_ID)); mineIDSign.put("signature", mineSigns.getString(MINE_ID_SIGN)); - boolean mineSignCheck = Authenticate - .verifySignature(mineIDSign.toString()); + + boolean mineSignCheck = Authenticate + .verifySignature(mineIDSign.toString()); + ArrayList ownersArray = new ArrayList(); ownersArray = IPFSNetwork.dhtOwnerCheck(MINE_ID); @@ -226,19 +228,18 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject "Staking pin check failed for DID: " + mineSigns .getString(STAKED_QUORUM_DID)); } - + if (mineSignCheck) { StakeConsensusLogger.debug( "########--Staking Complete " + STAKE_SUCCESS + "/5 !--########"); - qOut[j].println("staking-completed"); + // qOut[j].println("200"); StakeConsensusLogger.debug( "Staking completed for Peer: " + quorumPID[j]); stakeDetails.put(mineSigns); STAKE_SUCCESS++; } - } else { STAKE_FAILED++; StakeConsensusLogger.debug( @@ -275,7 +276,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } else if (qResponse[j] != null && qResponse[j].equals("446")) { STAKE_FAILED++; StakeConsensusLogger - .debug("Token files picked by quorum to stake is corroupted. Skipping...DID: " + .debug("No token is available to stake is corroupted. Skipping...DID: " + stakerDID); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); } else if (qResponse[j].equals("445")) { @@ -317,7 +318,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } do { - } while (STAKE_SUCCESS < 2 || STAKE_FAILED < 3); + } while (STAKE_SUCCESS < 3 && STAKE_FAILED < 3); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); diff --git a/src/com/rubix/Constants/MiningConstants.java b/src/com/rubix/Constants/MiningConstants.java index 5339da50..4d44faed 100644 --- a/src/com/rubix/Constants/MiningConstants.java +++ b/src/com/rubix/Constants/MiningConstants.java @@ -13,4 +13,5 @@ public class MiningConstants { public static final String MINED_RBT_SIGN = "minedTokenSignature"; public static final String MINE_ID_SIGN = "mineIDSignature"; public static final String QST_HEIGHT = "QSTHeight"; + public static final String QUORUM_SIGN_CONTENT = "quorumSignContent"; } \ No newline at end of file diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 85b5aa0d..2b08bb05 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -49,6 +49,7 @@ import com.rubix.Consensus.InitiatorConsensus; import com.rubix.Consensus.InitiatorProcedure; import com.rubix.Consensus.StakeConsensus; +import com.rubix.Constants.MiningConstants; import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; @@ -73,6 +74,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON StakeConsensus.STAKE_LOCKED = 0; StakeConsensus.STAKE_FAILED = 0; StakeConsensus.stakeDetails = new JSONArray(); + InitiatorConsensus.signedAphaQuorumArray = new JSONArray(); + InitiatorConsensus.quorumWithShares = new ArrayList<>(); + InitiatorConsensus.finalQuorumSignsArray = new JSONArray(); + InitiatorConsensus.quorumSignature = new JSONObject(); repo(ipfs); JSONObject APIResponse = new JSONObject(); JSONObject detailsObject = new JSONObject(data); @@ -183,7 +188,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } else ProofCreditsLogger.debug("GET request not worked"); - ProofCreditsLogger.debug("*************resJsonData.length()**********" + resJsonData.length()); // Check if node can mine token if (resJsonData.length() > 0) { // Calling Mine token function @@ -213,6 +217,14 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON String authSenderByRecHash = calculateHash(token + DID + comments, "SHA3-256"); String tid = calculateHash(authSenderByRecHash, "SHA3-256"); + // writeToFile(LOGGER_PATH + "tempbeta", tid.concat(DID), false); + // String betaHash = IPFSNetwork.add(LOGGER_PATH + "tempbeta", ipfs); + // deleteFile(LOGGER_PATH + "tempbeta"); + + // writeToFile(LOGGER_PATH + "tempgamma", tid.concat(DID), false); + // String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); + // deleteFile(LOGGER_PATH + "tempgamma"); + QuorumSwarmConnect(quorumArray, ipfs); alphaSize = quorumArray.length() - 14; @@ -371,8 +383,6 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON writeToFile(LOGGER_PATH + "tempToken", token.getString(i), false); String tokenHash = IPFSNetwork.add(LOGGER_PATH + "tempToken", ipfs); - writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); - deleteFile(LOGGER_PATH + "tempToken"); FileWriter shareWriter = new FileWriter(new File(LOGGER_PATH + "mycredit.txt"), true); shareWriter.write(InitiatorConsensus.quorumSignature.toString()); @@ -395,6 +405,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON int[] privateIntegerArray1 = strToIntArray(firstPrivate); String privateBinary = Functions.intArrayToStr(privateIntegerArray1); String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { positions += privateBinary.charAt(j); } @@ -421,12 +432,13 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON tokenChainGenesisObject.put("QSTHeight", QSTHeight); tokenChainGenesisObject.put("tokenHash", tokenHash); tokenChainGenesisObject.put("tokenContent", token.getString(i)); + tokenChainGenesisObject.put("nextHash", calculateHash(tid, "SHA3-256")); tokenChainGenesisObject.put("previousHash", ""); // stakingData = tokenChainGenesisObject; // tkHash = tokenHash; - tokenChainArray.put(tokenChainGenesisObject); + tokenChainArray.put(tokenChainGenesisObject); // ! new token will now need a staked token /* @@ -437,7 +449,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON Thread stakingThread = new Thread(() -> { try { StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, - tokenChainGenesisObject, ipfs, SEND_PORT + 3, + tokenChainGenesisObject, ipfs, SEND_PORT + 150, "alpha-stake-token"); } catch (Exception e) { e.printStackTrace(); @@ -445,15 +457,14 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON }); stakingThread.start(); - while ((StakeConsensus.STAKE_SUCCESS < 2 && StakeConsensus.STAKE_FAILED < 3)) { + while ((StakeConsensus.STAKE_SUCCESS < 3 && StakeConsensus.STAKE_FAILED < 3)) { } - ProofCreditsLogger.debug(StakeConsensus.STAKE_SUCCESS + "************" + StakeConsensus.STAKE_FAILED - + "******" + StakeConsensus.stakeDetails.length() + "<<<<<<<<<<<<<" - + StakeConsensus.stakeDetails.toString()); if (StakeConsensus.stakeDetails.length() > 0) { - tokenChainArray.put(StakeConsensus.stakeDetails); + tokenChainGenesisObject.put(MiningConstants.MINE_ID, StakeConsensus.stakeDetails); + tokenChainArray.put(tokenChainGenesisObject); + ProofCreditsLogger.debug("Stake Details for new mined token: " + StakeConsensus.stakeDetails); } else { updateQuorum(quorumArray, null, false, type); @@ -465,7 +476,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.warn("Staking failed"); return APIResponse; } - + writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); + ProofCreditsLogger.warn(" TOKENHASH " + tokenHash); + ProofCreditsLogger.warn(" TOKENS " + token.getString(i)); + deleteFile(LOGGER_PATH + "tempToken"); writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); JSONObject temp = new JSONObject(); temp.put("tokenHash", tokenHash); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index c75c8fc3..df9f3caa 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -54,6 +54,7 @@ import com.rubix.AuthenticateNode.Authenticate; import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Constants.MiningConstants; import com.rubix.Ping.VerifyStakedToken; import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; @@ -408,7 +409,7 @@ public static String receive() { JSONObject firstTCObject = tokenChain.getJSONObject(0); TokenReceiverLogger.debug("Last Object = " + lastObject); - if (lastObject.has("owner") && !lastObject.has(MINE_ID)) { + if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { TokenReceiverLogger.debug("Checking ownership"); String owner = lastObject.getString("owner"); @@ -450,11 +451,21 @@ public static String receive() { JSONObject genesiObject = tokenChain.getJSONObject(0); int randomNumber = new Random().nextInt(15); - JSONArray genesisSignaturesContentJSON = genesiObject.getJSONArray("quorumSigContent"); - JSONObject VerificationPick = genesisSignaturesContentJSON.getJSONObject(randomNumber); - if (VerificationPick.getString("hash") == genesiObject.getString("tid")) { + JSONObject genesisSignaturesContent = genesiObject + .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); + Iterator randomKey = genesisSignaturesContent.keys(); + for (int i = 0; i < randomNumber; i++) { + randomKey.next(); + } + String randomKeyString = randomKey.next().toString(); + JSONObject verificationPick = new JSONObject(); + verificationPick.put("did", randomKeyString); + verificationPick.put("hash", genesiObject.getString("tid")); + verificationPick.put("signature", genesisSignaturesContent.getString(randomKeyString)); + + if (verificationPick.getString("hash") == genesiObject.getString("tid")) { - if (Authenticate.verifySignature(VerificationPick.toString())) { + if (Authenticate.verifySignature(verificationPick.toString())) { TokenReceiverLogger.debug("Staking check (3) successful"); } else { TokenReceiverLogger.debug( @@ -567,46 +578,54 @@ public static String receive() { } } } - if (lastObject.has(MINE_ID)) { + if (lastObject.has(MiningConstants.STAKED_TOKEN)) { String mineID = lastObject.getString(MINE_ID); String mineIDContent = get(mineID, ipfs); JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - String stakerDID = mineIDContentJSON.getString(STAKED_QUORUM_DID); - String stakedToken = mineIDContentJSON.getString(STAKED_TOKEN); - String stakedTokenSign = mineIDContentJSON.getString(STAKED_TOKEN_SIGN); JSONObject tokenToVerify = new JSONObject(); - tokenToVerify.put("did", senderDidIpfsHash); - tokenToVerify.put("hash", stakedToken); - tokenToVerify.put("signature", stakedTokenSign); - if (Authenticate.verifySignature(tokenToVerify.toString())) { + if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { + + JSONObject stakeData = mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); + String stakerDID = stakeData.getString(STAKED_QUORUM_DID); + String stakedToken = stakeData.getString(STAKED_TOKEN); + String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); + + tokenToVerify.put("did", senderDidIpfsHash); + tokenToVerify.put("hash", stakedToken); + tokenToVerify.put("signature", stakedTokenSign); - boolean minedTokenStatus = true; - ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); - for (int i = 0; i < ownersArray.size(); i++) { - if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, stakedToken)) { - minedTokenStatus = false; + if (Authenticate.verifySignature(tokenToVerify.toString())) { + + boolean minedTokenStatus = true; + ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + for (int i = 0; i < ownersArray.size(); i++) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, stakedToken)) { + minedTokenStatus = false; + } } - } - if (!minedTokenStatus) { - TokenReceiverLogger.debug("Staking check failed: Found staked token but token height < 46"); + if (!minedTokenStatus) { + TokenReceiverLogger + .debug("Staking check failed: Found staked token but token height < 46"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); ownerCheck = false; invalidTokens.put(tokens); - } - - TokenReceiverLogger.debug( - "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); - ownerCheck = false; - invalidTokens.put(tokens); - } else { - TokenReceiverLogger.debug( - "Staking check failed: Found staked token but unable to verify staked token height"); - ownerCheck = false; - invalidTokens.put(tokens); + } else { + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to verify staked token height"); + ownerCheck = false; + invalidTokens.put(tokens); + } } + } // ! staking checks ends here } diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index f2956031..26dccee7 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -194,14 +194,16 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String tokenChainFileContent = readFile(TOKENCHAIN_PATH + wholeTokens.get(i) + ".json"); JSONArray tokenChainFileArray = new JSONArray(tokenChainFileContent); JSONArray previousSenderArray = new JSONArray(); - JSONObject lastObject = tokenChainFileArray.getJSONObject(tokenChainFileArray.length() - 1); - if (lastObject.has("mineID")) { - wholeTokens.remove(i); - } - for (int j = 0; j < tokenChainFileArray.length(); j++) { - String peerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", - tokenChainFileArray.getJSONObject(j).getString("sender")); - previousSenderArray.put(peerID); + + if (tokenChainFileArray.length() > 0) { + // JSONObject lastObject = + // tokenChainFileArray.getJSONObject(tokenChainFileArray.length() - 1); + + for (int j = 0; j < tokenChainFileArray.length(); j++) { + String peerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", + tokenChainFileArray.getJSONObject(j).getString("sender")); + previousSenderArray.put(peerID); + } } JSONObject previousSenderObject = new JSONObject(); @@ -717,8 +719,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception dataObject.put("gammaList", gammaPeersList); 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))) { TokenSenderLogger.debug("Consensus Failed"); senderDetails2Receiver.put("status", "Consensus Failed"); From ecbf63bc2bb3532d519093c663c2b4ecc64fc853 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Tue, 12 Apr 2022 13:58:37 +0530 Subject: [PATCH 103/179] commented unwanted code --- src/com/rubix/Mining/ProofCredits.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 2b08bb05..f6a0f058 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -438,7 +438,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // stakingData = tokenChainGenesisObject; // tkHash = tokenHash; - tokenChainArray.put(tokenChainGenesisObject); + //tokenChainArray.put(tokenChainGenesisObject); // ! new token will now need a staked token /* From f8c44a45aac7f66e023148f61acc4c934c5fc965 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 12 Apr 2022 15:40:29 +0530 Subject: [PATCH 104/179] receiver check update for single genesis object change Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index df9f3caa..19adde1b 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -449,6 +449,7 @@ public static String receive() { // ! staking checks (3): Verify the signatures earned during the mining of the // ! incoming mint token JSONObject genesiObject = tokenChain.getJSONObject(0); + JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); int randomNumber = new Random().nextInt(15); JSONObject genesisSignaturesContent = genesiObject @@ -489,9 +490,9 @@ public static String receive() { // ! staking checks (2): For incoming new mint token, verify the staked token - JSONObject oneOfThreeStake = tokenChain.getJSONObject(1); - JSONObject twoOfThreeStake = tokenChain.getJSONObject(2); - JSONObject threeOfThreeStake = tokenChain.getJSONObject(3); + JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); + JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); + JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); String[] stakedTokenTC = new String[3]; String[] stakedTokenSignTC = new String[3]; @@ -540,7 +541,7 @@ public static String receive() { .dhtOwnerCheck(stakedTokenTC[stakeCount]); for (int i = 0; i < ownersArray.size(); i++) { if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - stakedTokenTC[stakeCount])) { + genesiObject.getString("tokenContent"))) { minedTokenStatus = false; } } From 0d97fefa088ac474169bc425ea91ada3e2149868 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 12 Apr 2022 18:03:06 +0530 Subject: [PATCH 105/179] fix mined token height dulication Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 19adde1b..4b301c50 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -540,14 +540,14 @@ public static String receive() { ArrayList ownersArray = IPFSNetwork .dhtOwnerCheck(stakedTokenTC[stakeCount]); for (int i = 0; i < ownersArray.size(); i++) { - if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - genesiObject.getString("tokenContent"))) { + if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { minedTokenStatus = false; } } if (!minedTokenStatus) { TokenReceiverLogger.debug( - "Staking check failed: Found staked token but token height < 46"); + "Staked token is not found with staker DID: " + + stakerDIDTC[stakeCount]); ownerCheck = false; invalidTokens.put(tokens); } @@ -579,9 +579,12 @@ public static String receive() { } } } - if (lastObject.has(MiningConstants.STAKED_TOKEN)) { + if (lastObject.has(MiningConstants.STAKED_TOKEN) && tokenChain.length() > 1) { + + Boolean minedTokenStatus = true; String mineID = lastObject.getString(MINE_ID); + String mineIDContent = get(mineID, ipfs); JSONObject mineIDContentJSON = new JSONObject(mineIDContent); @@ -600,10 +603,10 @@ public static String receive() { if (Authenticate.verifySignature(tokenToVerify.toString())) { - boolean minedTokenStatus = true; ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); for (int i = 0; i < ownersArray.size(); i++) { - if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, stakedToken)) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + mineIDContentJSON.getString("tokenContent"))) { minedTokenStatus = false; } } From d1ad9b5e0dd6af18ee5dc59dab257ba163366ae8 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 13 Apr 2022 00:22:18 +0530 Subject: [PATCH 106/179] fix rec check for staked token Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Ping/VerifyStakedToken.java | 7 +- .../rubix/TokenTransfer/TokenReceiver.java | 102 +++++++++++------- 2 files changed, 68 insertions(+), 41 deletions(-) diff --git a/src/com/rubix/Ping/VerifyStakedToken.java b/src/com/rubix/Ping/VerifyStakedToken.java index d5c31713..bd599f54 100644 --- a/src/com/rubix/Ping/VerifyStakedToken.java +++ b/src/com/rubix/Ping/VerifyStakedToken.java @@ -27,7 +27,8 @@ public class VerifyStakedToken { private static final Logger PingSenderLogger = Logger.getLogger(VerifyStakedToken.class); public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); - public static boolean Contact(String pid, int port, String token) throws IOException, JSONException { + public static boolean Contact(String pid, int port, String tokenHash, String tokenContent) + throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -42,7 +43,7 @@ public static boolean Contact(String pid, int port, String token) throws IOExcep PrintStream output = new PrintStream(senderSocket.getOutputStream()); output.println("Get-TokenChain-Height"); - output.println(token); + output.println(tokenHash); String heightResponse; try { heightResponse = input.readLine(); @@ -80,7 +81,7 @@ public static boolean Contact(String pid, int port, String token) throws IOExcep height = Integer.parseInt(heightResponse); } - String tokenLevel = token.substring(0, 3); + String tokenLevel = tokenContent.substring(0, 3); int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); int requiredMinedTokenHeight = tokenLevelValue * 4; diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 4b301c50..8a0803b2 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -5,6 +5,7 @@ import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; +import static com.rubix.Constants.MiningConstants.STAKE_DATA; import static com.rubix.Resources.Functions.DATA_PATH; import static com.rubix.Resources.Functions.FunctionsLogger; import static com.rubix.Resources.Functions.IPFS_PORT; @@ -588,47 +589,72 @@ public static String receive() { String mineIDContent = get(mineID, ipfs); JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - JSONObject tokenToVerify = new JSONObject(); + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { - - JSONObject stakeData = mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); - String stakerDID = stakeData.getString(STAKED_QUORUM_DID); - String stakedToken = stakeData.getString(STAKED_TOKEN); - String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); - - tokenToVerify.put("did", senderDidIpfsHash); - tokenToVerify.put("hash", stakedToken); - tokenToVerify.put("signature", stakedTokenSign); - - if (Authenticate.verifySignature(tokenToVerify.toString())) { - - ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); - for (int i = 0; i < ownersArray.size(); i++) { - if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - mineIDContentJSON.getString("tokenContent"))) { - minedTokenStatus = false; - } - } - if (!minedTokenStatus) { - TokenReceiverLogger - .debug("Staking check failed: Found staked token but token height < 46"); - ownerCheck = false; - invalidTokens.put(tokens); - } - - TokenReceiverLogger.debug( - "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); - ownerCheck = false; - invalidTokens.put(tokens); - - } else { - TokenReceiverLogger.debug( - "Staking check failed: Found staked token but unable to verify staked token height"); - ownerCheck = false; - invalidTokens.put(tokens); + ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakeData.getString(STAKED_TOKEN)); + for (int i = 0; i < ownersArray.size(); i++) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + stakeData.getString( + STAKED_TOKEN), + mineIDContentJSON.getString("tokenContent"))) { + minedTokenStatus = false; } } + if (!minedTokenStatus) { + TokenReceiverLogger + .debug("Staking check failed: Found staked token but token height < 46"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); + ownerCheck = false; + invalidTokens.put(tokens); + + // JSONObject tokenToVerify = new JSONObject(); + // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { + + // JSONObject stakeData = + // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); + // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); + // String stakedToken = stakeData.getString(STAKED_TOKEN); + // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); + + // tokenToVerify.put("did", senderDidIpfsHash); + // tokenToVerify.put("hash", stakedToken); + // tokenToVerify.put("signature", stakedTokenSign); + + // if (Authenticate.verifySignature(tokenToVerify.toString())) { + + // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + // for (int i = 0; i < ownersArray.size(); i++) { + // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + // mineIDContentJSON.getString("tokenContent"))) { + // minedTokenStatus = false; + // } + // } + // if (!minedTokenStatus) { + // TokenReceiverLogger + // .debug("Staking check failed: Found staked token but token height < 46"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to transfer while mined + // token height is not satisfied for the network"); + // ownerCheck = false; + // invalidTokens.put(tokens); + + // } else { + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to verify staked token + // height"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + // } } // ! staking checks ends here From 1c0b84aa2011eff64cf56ffebfa3b84245a5323a Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 13 Apr 2022 00:33:48 +0530 Subject: [PATCH 107/179] revert change to STAKE_FAILED variable Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 8d70bcfb..b1981b3d 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -211,10 +211,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject mineIDSign.put("hash", mineSigns.getString(MINE_ID)); mineIDSign.put("signature", mineSigns.getString(MINE_ID_SIGN)); - - boolean mineSignCheck = Authenticate - .verifySignature(mineIDSign.toString()); - + + boolean mineSignCheck = Authenticate + .verifySignature(mineIDSign.toString()); ArrayList ownersArray = new ArrayList(); ownersArray = IPFSNetwork.dhtOwnerCheck(MINE_ID); @@ -224,17 +223,20 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .debug("Staking pin check passed: " + mineSigns .getString(STAKED_QUORUM_DID)); } else { + STAKE_FAILED++; + IPFSNetwork.executeIPFSCommands( + "ipfs p2p close -t /p2p/" + quorumPID[j]); StakeConsensusLogger.debug( "Staking pin check failed for DID: " + mineSigns .getString(STAKED_QUORUM_DID)); } - + if (mineSignCheck) { StakeConsensusLogger.debug( "########--Staking Complete " + STAKE_SUCCESS + "/5 !--########"); - // qOut[j].println("200"); + // qOut[j].println("200"); StakeConsensusLogger.debug( "Staking completed for Peer: " + quorumPID[j]); stakeDetails.put(mineSigns); @@ -252,6 +254,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } } catch (SocketException e) { + STAKE_FAILED++; StakeConsensusLogger .debug("Mined Token Details validation failed for DID: " + stakerDID + " Received null response"); @@ -268,6 +271,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } } catch (SocketException e) { + STAKE_FAILED++; StakeConsensusLogger .debug("Mined Token Details validation failed. Received null response"); IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumPID[j]); @@ -296,6 +300,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } } catch (SocketException e) { + STAKE_FAILED++; StakeConsensusLogger .debug("Mined Token Details validation failed for DID: " + stakerDID + " Received null response"); @@ -305,6 +310,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } } catch (Exception e) { + STAKE_FAILED++; StakeConsensusLogger.error("Error in quorum consensus thread: " + e); } StakeConsensusLogger.debug("*******STAKE_SUCCESS********* " + STAKE_SUCCESS From 95ac93f814302d27ab31643dde2147fb3f4ae3bd Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 13 Apr 2022 00:46:04 +0530 Subject: [PATCH 108/179] exit condition fix Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index b1981b3d..cd9b017e 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -324,7 +324,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } do { - } while (STAKE_SUCCESS < 3 && STAKE_FAILED < 3); + } while (STAKE_SUCCESS < 2 && STAKE_FAILED < 2); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); From aa107f2db4ce849b3c57a2f256f3a39a185fa5f4 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Wed, 13 Apr 2022 08:56:53 +0530 Subject: [PATCH 109/179] issue fix - fetched Mining data based on the new format --- src/com/rubix/TokenTransfer/TokenReceiver.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 8a0803b2..b7085b81 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -523,9 +523,12 @@ public static String receive() { String mineIDContent = get(mineIDTC[0], ipfs); JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - String stakerDIDMineData = mineIDContentJSON.getString(STAKED_QUORUM_DID); - String stakedTokenMineData = mineIDContentJSON.getString(STAKED_TOKEN); - String stakedTokenSignMineData = mineIDContentJSON.getString(STAKED_TOKEN_SIGN); + + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); + + String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); + String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); + String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) && stakedTokenTC[stakeCount].equals(stakedTokenMineData) From 2387866b2324730f778fa2a380b60eac1a13d975 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Wed, 13 Apr 2022 14:27:34 +0530 Subject: [PATCH 110/179] Mined token was nt able to transfer - fixed --- src/com/rubix/Consensus/StakeConsensus.java | 16 ++++++----- src/com/rubix/Mining/ProofCredits.java | 26 +++++++++--------- .../rubix/TokenTransfer/TokenReceiver.java | 27 ++++++++++++------- 3 files changed, 41 insertions(+), 28 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index cd9b017e..3ba3de33 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -152,7 +152,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject if (!owner.equals(ownerRecalculated)) { ownerCheck = false; - STAKE_FAILED++; + // STAKE_FAILED++; StakeConsensusLogger.debug( "Ownership Check Failed for index " + j + " with DID: " + owner); @@ -162,7 +162,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } } else { - STAKE_FAILED++; + ownerCheck = false; + // STAKE_FAILED++; StakeConsensusLogger .debug("insufficient stake token height details from DID: " + stakerDID); @@ -212,9 +213,6 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject mineIDSign.put("signature", mineSigns.getString(MINE_ID_SIGN)); - boolean mineSignCheck = Authenticate - .verifySignature(mineIDSign.toString()); - ArrayList ownersArray = new ArrayList(); ownersArray = IPFSNetwork.dhtOwnerCheck(MINE_ID); @@ -223,7 +221,6 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .debug("Staking pin check passed: " + mineSigns .getString(STAKED_QUORUM_DID)); } else { - STAKE_FAILED++; IPFSNetwork.executeIPFSCommands( "ipfs p2p close -t /p2p/" + quorumPID[j]); StakeConsensusLogger.debug( @@ -231,6 +228,9 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject .getString(STAKED_QUORUM_DID)); } + boolean mineSignCheck = Authenticate + .verifySignature(mineIDSign.toString()); + if (mineSignCheck) { StakeConsensusLogger.debug( "########--Staking Complete " + STAKE_SUCCESS @@ -241,6 +241,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject "Staking completed for Peer: " + quorumPID[j]); stakeDetails.put(mineSigns); STAKE_SUCCESS++; + }else { + STAKE_FAILED++; } } else { STAKE_FAILED++; @@ -324,7 +326,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject } do { - } while (STAKE_SUCCESS < 2 && STAKE_FAILED < 2); + } while (STAKE_SUCCESS < 3 && STAKE_FAILED < 3); } catch (Exception e) { StakeConsensusLogger.error("Error in getStakeConsensus: " + e); diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index f6a0f058..9e45ae2b 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -449,7 +449,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON Thread stakingThread = new Thread(() -> { try { StakeConsensus.getStakeConsensus(InitiatorConsensus.signedAphaQuorumArray, - tokenChainGenesisObject, ipfs, SEND_PORT + 150, + tokenChainGenesisObject, ipfs, SEND_PORT + 3, "alpha-stake-token"); } catch (Exception e) { e.printStackTrace(); @@ -461,11 +461,21 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } - if (StakeConsensus.stakeDetails.length() > 0) { + if (StakeConsensus.STAKE_SUCCESS == 3 && StakeConsensus.stakeDetails.length() > 0) { tokenChainGenesisObject.put(MiningConstants.MINE_ID, StakeConsensus.stakeDetails); tokenChainArray.put(tokenChainGenesisObject); ProofCreditsLogger.debug("Stake Details for new mined token: " + StakeConsensus.stakeDetails); + writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); + ProofCreditsLogger.warn(" TOKENHASH " + tokenHash); + ProofCreditsLogger.warn(" TOKENS " + token.getString(i)); + deleteFile(LOGGER_PATH + "tempToken"); + writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); + JSONObject temp = new JSONObject(); + temp.put("tokenHash", tokenHash); + JSONArray tempArray = new JSONArray(); + tempArray.put(temp); + updateJSON("add", PAYMENTS_PATH + "BNK00.json", tempArray.toString()); } else { updateQuorum(quorumArray, null, false, type); APIResponse.put("did", DID); @@ -476,16 +486,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.warn("Staking failed"); return APIResponse; } - writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); - ProofCreditsLogger.warn(" TOKENHASH " + tokenHash); - ProofCreditsLogger.warn(" TOKENS " + token.getString(i)); - deleteFile(LOGGER_PATH + "tempToken"); - writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", tokenChainArray.toString(), false); - JSONObject temp = new JSONObject(); - temp.put("tokenHash", tokenHash); - JSONArray tempArray = new JSONArray(); - tempArray.put(temp); - updateJSON("add", PAYMENTS_PATH + "BNK00.json", tempArray.toString()); + + } // updateJSON("add", TOKENCHAIN_PATH + tkHash + ".json", tempArray.toString()); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index b7085b81..79cd715d 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -459,13 +459,13 @@ public static String receive() { for (int i = 0; i < randomNumber; i++) { randomKey.next(); } - String randomKeyString = randomKey.next().toString(); + /** String randomKeyString = randomKey.next().toString(); JSONObject verificationPick = new JSONObject(); verificationPick.put("did", randomKeyString); verificationPick.put("hash", genesiObject.getString("tid")); verificationPick.put("signature", genesisSignaturesContent.getString(randomKeyString)); - if (verificationPick.getString("hash") == genesiObject.getString("tid")) { + if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) { if (Authenticate.verifySignature(verificationPick.toString())) { TokenReceiverLogger.debug("Staking check (3) successful"); @@ -481,7 +481,7 @@ public static String receive() { ownerCheck = false; invalidTokens.put(tokens); } - + */ // else { // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not // found"); @@ -521,8 +521,9 @@ public static String receive() { for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { - String mineIDContent = get(mineIDTC[0], ipfs); + String mineIDContent = get(mineIDTC[stakeCount], ipfs); JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + TokenReceiverLogger.debug(mineIDContentJSON.toString()); JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); @@ -530,14 +531,22 @@ public static String receive() { String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); + TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); + + TokenReceiverLogger.debug(stakerDIDMineData); + TokenReceiverLogger.debug(stakedTokenMineData); + TokenReceiverLogger.debug(stakedTokenSignMineData); + if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) && stakedTokenTC[stakeCount].equals(stakedTokenMineData) && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakerDIDTC); - detailsToVerify.put("hash", mineIDTC); - detailsToVerify.put("signature", mineIDSignTC); + detailsToVerify.put("did", stakerDIDTC[stakeCount]); + detailsToVerify.put("hash", mineIDTC[stakeCount]); + detailsToVerify.put("signature", mineIDSignTC[stakeCount]); if (Authenticate.verifySignature(detailsToVerify.toString())) { boolean minedTokenStatus = true; @@ -559,14 +568,14 @@ public static String receive() { } else { TokenReceiverLogger.debug( "Staking check (2) failed - unable to verify mine ID signature by staker: " - + stakerDIDTC); + + stakerDIDTC[stakeCount]); ownerCheck = false; invalidTokens.put(tokens); } TokenReceiverLogger .debug("MineID Verification Successful with Staking node: " - + stakerDIDTC); + + stakerDIDTC[stakeCount]); } else { TokenReceiverLogger.debug("Staking check (2) failed"); ownerCheck = false; From 15075a7ceceadbb28907d5b061827f93157278de Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Wed, 13 Apr 2022 17:57:59 +0530 Subject: [PATCH 111/179] Included check to verify if staked token is available --- .../rubix/TokenTransfer/TokenReceiver.java | 184 ++++++++++-------- 1 file changed, 98 insertions(+), 86 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 79cd715d..9e3bda50 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -490,106 +490,116 @@ public static String receive() { // } // ! staking checks (2): For incoming new mint token, verify the staked token - - JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); - JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); - JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); - - String[] stakedTokenTC = new String[3]; - String[] stakedTokenSignTC = new String[3]; - String[] stakerDIDTC = new String[3]; - String[] mineIDTC = new String[3]; - String[] mineIDSignTC = new String[3]; - - stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); - mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); - mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); - mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); - - for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { - - String mineIDContent = get(mineIDTC[stakeCount], ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - TokenReceiverLogger.debug(mineIDContentJSON.toString()); - - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - - String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); - String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); - String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); - - TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); - - TokenReceiverLogger.debug(stakerDIDMineData); - TokenReceiverLogger.debug(stakedTokenMineData); - TokenReceiverLogger.debug(stakedTokenSignMineData); - - if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) - && stakedTokenTC[stakeCount].equals(stakedTokenMineData) - && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakerDIDTC[stakeCount]); - detailsToVerify.put("hash", mineIDTC[stakeCount]); - detailsToVerify.put("signature", mineIDSignTC[stakeCount]); - if (Authenticate.verifySignature(detailsToVerify.toString())) { - - boolean minedTokenStatus = true; - ArrayList ownersArray = IPFSNetwork - .dhtOwnerCheck(stakedTokenTC[stakeCount]); - for (int i = 0; i < ownersArray.size(); i++) { - if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { - minedTokenStatus = false; + + if(stakeDataArray.length() == 3) { + + JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); + JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); + JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); + + String[] stakedTokenTC = new String[3]; + String[] stakedTokenSignTC = new String[3]; + String[] stakerDIDTC = new String[3]; + String[] mineIDTC = new String[3]; + String[] mineIDSignTC = new String[3]; + + stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); + mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); + mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); + mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); + + for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { + + String mineIDContent = get(mineIDTC[stakeCount], ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + TokenReceiverLogger.debug(mineIDContentJSON.toString()); + + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); + + String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); + String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); + String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); + + TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); + + TokenReceiverLogger.debug(stakerDIDMineData); + TokenReceiverLogger.debug(stakedTokenMineData); + TokenReceiverLogger.debug(stakedTokenSignMineData); + + if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) + && stakedTokenTC[stakeCount].equals(stakedTokenMineData) + && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakerDIDTC[stakeCount]); + detailsToVerify.put("hash", mineIDTC[stakeCount]); + detailsToVerify.put("signature", mineIDSignTC[stakeCount]); + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + boolean minedTokenStatus = true; + ArrayList ownersArray = IPFSNetwork + .dhtOwnerCheck(stakedTokenTC[stakeCount]); + for (int i = 0; i < ownersArray.size(); i++) { + if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { + minedTokenStatus = false; + } } - } - if (!minedTokenStatus) { + if (!minedTokenStatus) { + TokenReceiverLogger.debug( + "Staked token is not found with staker DID: " + + stakerDIDTC[stakeCount]); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { TokenReceiverLogger.debug( - "Staked token is not found with staker DID: " + "Staking check (2) failed - unable to verify mine ID signature by staker: " + stakerDIDTC[stakeCount]); ownerCheck = false; invalidTokens.put(tokens); } - } else { - TokenReceiverLogger.debug( - "Staking check (2) failed - unable to verify mine ID signature by staker: " + TokenReceiverLogger + .debug("MineID Verification Successful with Staking node: " + stakerDIDTC[stakeCount]); + } else { + TokenReceiverLogger.debug("Staking check (2) failed"); ownerCheck = false; invalidTokens.put(tokens); } - TokenReceiverLogger - .debug("MineID Verification Successful with Staking node: " - + stakerDIDTC[stakeCount]); - } else { - TokenReceiverLogger.debug("Staking check (2) failed"); - ownerCheck = false; - invalidTokens.put(tokens); + TokenReceiverLogger.debug("Staking check (2) successful"); + // } else { + // TokenReceiverLogger.debug( + // "Staking check (2) failed: Could not verify mine ID signature"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } } - - TokenReceiverLogger.debug("Staking check (2) successful"); - // } else { - // TokenReceiverLogger.debug( - // "Staking check (2) failed: Could not verify mine ID signature"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } + + }else { + ownerCheck = false; + TokenReceiverLogger.debug("Staked Token is not available!"); + } + + } } if (lastObject.has(MiningConstants.STAKED_TOKEN) && tokenChain.length() > 1) { @@ -671,6 +681,8 @@ public static String receive() { } // ! staking checks ends here } + + if (!ownerCheck) { TokenReceiverLogger.debug("Ownership Check Failed"); From dd73170cd74214b1babd4e72e0498d03db26c4d4 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Fri, 15 Apr 2022 19:00:43 +0530 Subject: [PATCH 112/179] Excluded Path in check for Version Compatibility --- src/com/rubix/Ping/PingCheck.java | 22 +++++++++++----------- src/com/rubix/Ping/PingReceive.java | 2 +- src/com/rubix/Resources/Functions.java | 4 ++++ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index 6500636d..538388ed 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -82,8 +82,17 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE return APIResponse; } - if (pongResponse != null && (!pongResponse.equals(initHash()))) { - executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + if (pongResponse != null && (pongResponse.equals(initHash()))) { + + PingSenderLogger.info("Ping Successful"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Success"); + APIResponse.put("message", "Ping Check Success"); + } else { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); PingSenderLogger.info("Pong response not received"); output.close(); input.close(); @@ -91,15 +100,6 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong response not received"); - } else { - PingSenderLogger.info("Ping Successful"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); - output.close(); - input.close(); - senderSocket.close(); - APIResponse.put("status", "Success"); - APIResponse.put("message", "Ping Check Success"); - } return APIResponse; } diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index 966f5234..b4a55336 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -79,7 +79,7 @@ public static String receive(int port) throws JSONException { PingReceiverLogger.debug("Ping Request Received: " + pingRequest); if (pingRequest != null && pingRequest.contains("PingCheck")) { output.println(initHash()); - + APIResponse.put("status", "Success"); APIResponse.put("message", "Pong Sent to Sender with Check Sum"); PingReceiverLogger.info("Pong Sent"); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 93ea2850..935edad9 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1434,6 +1434,8 @@ public static String initHash() throws IOException { String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); initPath = initPath.split("\\.jar")[0]; initPath = initPath.split("file:", 2)[1]; + String jarName[] = initPath.split("\\/"); + initPath = jarName[jarName.length-1]; initPath = initPath + ".jar"; String hash = calculateFileHash(initPath, "SHA3-256"); return hash; @@ -1597,6 +1599,8 @@ public static boolean checkIPFSStatus(String peerid, IPFS ipfs) { public static boolean ping(String peerid, int port) throws IOException, JSONException { JSONObject pingCheck = PingCheck.Ping(peerid, port); + FunctionsLogger.info("Ping Check Response " + pingCheck); + if (pingCheck.getString("status").contains("Failed")) { return false; } else From 51da0b0d5163f8785e771c0d62e66e460cfbbfb0 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sat, 16 Apr 2022 16:54:38 +0530 Subject: [PATCH 113/179] hash table for token rec Signed-off-by: Nidhin Mahesh A --- .../rubix/TokenTransfer/TokenReceiver.java | 505 +++++++++--------- 1 file changed, 263 insertions(+), 242 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 9e3bda50..996427da 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -7,7 +7,7 @@ import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Constants.MiningConstants.STAKE_DATA; import static com.rubix.Resources.Functions.DATA_PATH; -import static com.rubix.Resources.Functions.FunctionsLogger; +import static com.rubix.Resources.Functions.*; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; import static com.rubix.Resources.Functions.PAYMENTS_PATH; @@ -75,6 +75,10 @@ public class TokenReceiver { private static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); private static String SenWalletBin; + // token limit for each level + private static final int[] tokenLimit = { 0, 5000000, 2425000, 2303750, 2188563, 2079134, 1975178, 1876419, 1782598, + 1693468, 1608795, 1528355, 1451937, 1379340 }; + /** * Receiver Node: To receive a valid token from an authentic sender * @@ -406,283 +410,300 @@ public static String receive() { String tokens = null; JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); - JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); - JSONObject firstTCObject = tokenChain.getJSONObject(0); - TokenReceiverLogger.debug("Last Object = " + lastObject); - - if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { - - TokenReceiverLogger.debug("Checking ownership"); - String owner = lastObject.getString("owner"); - tokens = allTokens.getString(count); - String hashString = tokens.concat(senderDidIpfsHash); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); - String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); - - TokenReceiverLogger.debug("Ownership Here Sender Calculation"); - TokenReceiverLogger.debug("tokens: " + tokens); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); - - if (!owner.equals(ownerRecalculated)) { - ownerCheck = false; - invalidTokens.put(tokens); - } + String TokenContent = get(wholeTokens.getString(count), ipfs); + String tokenLevel = TokenContent.substring(0, 3); + String tokenNumberHash = TokenContent.substring(3, TokenContent.indexOf("\n")); + + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLimitForLevel = tokenLimit[tokenLevelInt]; + int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + int minumumStakeHeight = tokenLevelValue * 4; + int tokenNumber = 1204401; + + // check TokenHashTable exists + File tokenHashTable = new File( + WALLET_DATA_PATH.concat("TokenHashTable").concat(".json")); + if (!tokenHashTable.exists()) { + tokenHashTable.createNewFile(); + writeToFile(tokenHashTable.toString(), , false); + } - // ! staking checks (1..4) starts here - - // ! staking checks (1): Check incoming token level - String TokenContent = get(wholeTokens.getString(count), ipfs); - String tokenLevel = TokenContent.substring(0, 3); - int tokenLevelInt = Integer.parseInt(tokenLevel); - int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); - int minumumStakeHeight = tokenLevelValue * 4; - int tokenNumber = 1204400; - - if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) - && firstTCObject.has("QSTHeight")) { - // && (tokenNumber > 1204400) - - // ! staking checks (3): Verify the signatures earned during the mining of the - // ! incoming mint token - JSONObject genesiObject = tokenChain.getJSONObject(0); - JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); - - int randomNumber = new Random().nextInt(15); - JSONObject genesisSignaturesContent = genesiObject - .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); - Iterator randomKey = genesisSignaturesContent.keys(); - for (int i = 0; i < randomNumber; i++) { - randomKey.next(); - } - /** String randomKeyString = randomKey.next().toString(); - JSONObject verificationPick = new JSONObject(); - verificationPick.put("did", randomKeyString); - verificationPick.put("hash", genesiObject.getString("tid")); - verificationPick.put("signature", genesisSignaturesContent.getString(randomKeyString)); + // if not create new one - if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) { + if (tokenChain.length() > 0 || (tokenNumber >= 1204400 && (tokenLevelInt >= 4))) { - if (Authenticate.verifySignature(verificationPick.toString())) { - TokenReceiverLogger.debug("Staking check (3) successful"); - } else { - TokenReceiverLogger.debug( - "Staking check (3) failed: Could not verify genesis credit signature"); - ownerCheck = false; - invalidTokens.put(tokens); - } - } else { - TokenReceiverLogger.debug( - "Staking check (3) failed: Genesis TID is not equal to the hash of the genesis signature"); + JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); + JSONObject firstTCObject = tokenChain.getJSONObject(0); + TokenReceiverLogger.debug("Last Object = " + lastObject); + + if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { + + TokenReceiverLogger.debug("Checking ownership"); + String owner = lastObject.getString("owner"); + tokens = allTokens.getString(count); + String hashString = tokens.concat(senderDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); + String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here Sender Calculation"); + TokenReceiverLogger.debug("tokens: " + tokens); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); + + if (!owner.equals(ownerRecalculated)) { ownerCheck = false; invalidTokens.put(tokens); } - */ - // else { - // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not - // found"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - // ! staking checks (2): For incoming new mint token, verify the staked token - - if(stakeDataArray.length() == 3) { - - JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); - JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); - JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); - - String[] stakedTokenTC = new String[3]; - String[] stakedTokenSignTC = new String[3]; - String[] stakerDIDTC = new String[3]; - String[] mineIDTC = new String[3]; - String[] mineIDSignTC = new String[3]; - - stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); - mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); - mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); - mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); - - for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { - - String mineIDContent = get(mineIDTC[stakeCount], ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - TokenReceiverLogger.debug(mineIDContentJSON.toString()); - - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - - String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); - String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); - String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); - - TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); - - TokenReceiverLogger.debug(stakerDIDMineData); - TokenReceiverLogger.debug(stakedTokenMineData); - TokenReceiverLogger.debug(stakedTokenSignMineData); - - if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) - && stakedTokenTC[stakeCount].equals(stakedTokenMineData) - && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakerDIDTC[stakeCount]); - detailsToVerify.put("hash", mineIDTC[stakeCount]); - detailsToVerify.put("signature", mineIDSignTC[stakeCount]); - if (Authenticate.verifySignature(detailsToVerify.toString())) { - - boolean minedTokenStatus = true; - ArrayList ownersArray = IPFSNetwork - .dhtOwnerCheck(stakedTokenTC[stakeCount]); - for (int i = 0; i < ownersArray.size(); i++) { - if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { - minedTokenStatus = false; + // ! staking checks (1..4) starts here + + // ! staking checks (1): Check incoming token level + + if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) + && firstTCObject.has("QSTHeight")) { + // && (tokenNumber > 1204400) + + // ! staking checks (3): Verify the signatures earned during the mining of the + // ! incoming mint token + JSONObject genesiObject = tokenChain.getJSONObject(0); + JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); + + int randomNumber = new Random().nextInt(15); + JSONObject genesisSignaturesContent = genesiObject + .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); + Iterator randomKey = genesisSignaturesContent.keys(); + for (int i = 0; i < randomNumber; i++) { + randomKey.next(); + } + /** + * String randomKeyString = randomKey.next().toString(); + * JSONObject verificationPick = new JSONObject(); + * verificationPick.put("did", randomKeyString); + * verificationPick.put("hash", genesiObject.getString("tid")); + * verificationPick.put("signature", + * genesisSignaturesContent.getString(randomKeyString)); + * + * if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) + * { + * + * if (Authenticate.verifySignature(verificationPick.toString())) { + * TokenReceiverLogger.debug("Staking check (3) successful"); + * } else { + * TokenReceiverLogger.debug( + * "Staking check (3) failed: Could not verify genesis credit signature"); + * ownerCheck = false; + * invalidTokens.put(tokens); + * } + * } else { + * TokenReceiverLogger.debug( + * "Staking check (3) failed: Genesis TID is not equal to the hash of the + * genesis signature"); + * ownerCheck = false; + * invalidTokens.put(tokens); + * } + */ + // else { + // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not + // found"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + + // ! staking checks (2): For incoming new mint token, verify the staked token + + if (stakeDataArray.length() == 3) { + + JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); + JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); + JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); + + String[] stakedTokenTC = new String[3]; + String[] stakedTokenSignTC = new String[3]; + String[] stakerDIDTC = new String[3]; + String[] mineIDTC = new String[3]; + String[] mineIDSignTC = new String[3]; + + stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); + mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); + mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); + mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); + + for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { + + String mineIDContent = get(mineIDTC[stakeCount], ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + TokenReceiverLogger.debug(mineIDContentJSON.toString()); + + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); + + String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); + String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); + String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); + + TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); + + TokenReceiverLogger.debug(stakerDIDMineData); + TokenReceiverLogger.debug(stakedTokenMineData); + TokenReceiverLogger.debug(stakedTokenSignMineData); + + if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) + && stakedTokenTC[stakeCount].equals(stakedTokenMineData) + && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakerDIDTC[stakeCount]); + detailsToVerify.put("hash", mineIDTC[stakeCount]); + detailsToVerify.put("signature", mineIDSignTC[stakeCount]); + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + boolean minedTokenStatus = true; + ArrayList ownersArray = IPFSNetwork + .dhtOwnerCheck(stakedTokenTC[stakeCount]); + for (int i = 0; i < ownersArray.size(); i++) { + if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { + minedTokenStatus = false; + } } - } - if (!minedTokenStatus) { + if (!minedTokenStatus) { + TokenReceiverLogger.debug( + "Staked token is not found with staker DID: " + + stakerDIDTC[stakeCount]); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { TokenReceiverLogger.debug( - "Staked token is not found with staker DID: " + "Staking check (2) failed - unable to verify mine ID signature by staker: " + stakerDIDTC[stakeCount]); ownerCheck = false; invalidTokens.put(tokens); } - } else { - TokenReceiverLogger.debug( - "Staking check (2) failed - unable to verify mine ID signature by staker: " + TokenReceiverLogger + .debug("MineID Verification Successful with Staking node: " + stakerDIDTC[stakeCount]); + } else { + TokenReceiverLogger.debug("Staking check (2) failed"); ownerCheck = false; invalidTokens.put(tokens); } - TokenReceiverLogger - .debug("MineID Verification Successful with Staking node: " - + stakerDIDTC[stakeCount]); - } else { - TokenReceiverLogger.debug("Staking check (2) failed"); - ownerCheck = false; - invalidTokens.put(tokens); + TokenReceiverLogger.debug("Staking check (2) successful"); + // } else { + // TokenReceiverLogger.debug( + // "Staking check (2) failed: Could not verify mine ID signature"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } } - TokenReceiverLogger.debug("Staking check (2) successful"); - // } else { - // TokenReceiverLogger.debug( - // "Staking check (2) failed: Could not verify mine ID signature"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } + } else { + ownerCheck = false; + TokenReceiverLogger.debug("Staked Token is not available!"); + } - - }else { - ownerCheck = false; - TokenReceiverLogger.debug("Staked Token is not available!"); - - } - + } } - } - if (lastObject.has(MiningConstants.STAKED_TOKEN) && tokenChain.length() > 1) { + if (lastObject.has(MiningConstants.STAKED_TOKEN) && tokenChain.length() > 1) { - Boolean minedTokenStatus = true; + Boolean minedTokenStatus = true; - String mineID = lastObject.getString(MINE_ID); + String mineID = lastObject.getString(MINE_ID); - String mineIDContent = get(mineID, ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + String mineIDContent = get(mineID, ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakeData.getString(STAKED_TOKEN)); - for (int i = 0; i < ownersArray.size(); i++) { - if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - stakeData.getString( - STAKED_TOKEN), - mineIDContentJSON.getString("tokenContent"))) { - minedTokenStatus = false; + ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakeData.getString(STAKED_TOKEN)); + for (int i = 0; i < ownersArray.size(); i++) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + stakeData.getString( + STAKED_TOKEN), + mineIDContentJSON.getString("tokenContent"))) { + minedTokenStatus = false; + } } - } - if (!minedTokenStatus) { - TokenReceiverLogger - .debug("Staking check failed: Found staked token but token height < 46"); + if (!minedTokenStatus) { + TokenReceiverLogger + .debug("Staking check failed: Found staked token but token height < 46"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); ownerCheck = false; invalidTokens.put(tokens); - } - TokenReceiverLogger.debug( - "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); - ownerCheck = false; - invalidTokens.put(tokens); - - // JSONObject tokenToVerify = new JSONObject(); - // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { - - // JSONObject stakeData = - // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); - // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); - // String stakedToken = stakeData.getString(STAKED_TOKEN); - // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); - - // tokenToVerify.put("did", senderDidIpfsHash); - // tokenToVerify.put("hash", stakedToken); - // tokenToVerify.put("signature", stakedTokenSign); - - // if (Authenticate.verifySignature(tokenToVerify.toString())) { - - // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); - // for (int i = 0; i < ownersArray.size(); i++) { - // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - // mineIDContentJSON.getString("tokenContent"))) { - // minedTokenStatus = false; - // } - // } - // if (!minedTokenStatus) { - // TokenReceiverLogger - // .debug("Staking check failed: Found staked token but token height < 46"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - - // TokenReceiverLogger.debug( - // "Staking check failed: Found staked token but unable to transfer while mined - // token height is not satisfied for the network"); - // ownerCheck = false; - // invalidTokens.put(tokens); - - // } else { - // TokenReceiverLogger.debug( - // "Staking check failed: Found staked token but unable to verify staked token - // height"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - // } + // JSONObject tokenToVerify = new JSONObject(); + // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { + + // JSONObject stakeData = + // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); + // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); + // String stakedToken = stakeData.getString(STAKED_TOKEN); + // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); + // tokenToVerify.put("did", senderDidIpfsHash); + // tokenToVerify.put("hash", stakedToken); + // tokenToVerify.put("signature", stakedTokenSign); + + // if (Authenticate.verifySignature(tokenToVerify.toString())) { + + // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + // for (int i = 0; i < ownersArray.size(); i++) { + // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + // mineIDContentJSON.getString("tokenContent"))) { + // minedTokenStatus = false; + // } + // } + // if (!minedTokenStatus) { + // TokenReceiverLogger + // .debug("Staking check failed: Found staked token but token height < 46"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to transfer while mined + // token height is not satisfied for the network"); + // ownerCheck = false; + // invalidTokens.put(tokens); + + // } else { + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to verify staked token + // height"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + // } + + } } - // ! staking checks ends here } - - if (!ownerCheck) { TokenReceiverLogger.debug("Ownership Check Failed"); From d2e385e139f30d2140142315c86e45dfde1fd9bc Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Sat, 16 Apr 2022 16:55:18 +0530 Subject: [PATCH 114/179] hash table check Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 996427da..ddd6a364 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -7,7 +7,7 @@ import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; import static com.rubix.Constants.MiningConstants.STAKE_DATA; import static com.rubix.Resources.Functions.DATA_PATH; -import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.Functions.FunctionsLogger; import static com.rubix.Resources.Functions.IPFS_PORT; import static com.rubix.Resources.Functions.LOGGER_PATH; import static com.rubix.Resources.Functions.PAYMENTS_PATH; @@ -425,7 +425,19 @@ public static String receive() { WALLET_DATA_PATH.concat("TokenHashTable").concat(".json")); if (!tokenHashTable.exists()) { tokenHashTable.createNewFile(); - writeToFile(tokenHashTable.toString(), , false); + JSONObject tokenHashTableJSON = new JSONObject(); + for (int i = 1; i <= 5000000; i++) { + tokenHashTableJSON.put(calculateHash(String.valueOf(i), "SHA-256"), i); + } + writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); + } + String tokenHashTableData = readFile(tokenHashTable.toString()); + JSONObject tokenHashTableJSON = new JSONObject(tokenHashTableData); + if (tokenHashTableJSON.has(tokenNumberHash)) { + tokenNumber = tokenHashTableJSON.getInt(tokenNumberHash); + TokenReceiverLogger.debug("Token Number: " + tokenNumber); + } else { + TokenReceiverLogger.debug("token : " + tokenNumberHash + " not found in TokenHashTable"); } // if not create new one From 82fe3d5762342854bbb5cea526b158b7844b19ae Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Mon, 18 Apr 2022 10:11:54 +0530 Subject: [PATCH 115/179] included socket time out --- src/com/rubix/Ping/PingCheck.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index 538388ed..0c5406c9 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -28,7 +28,8 @@ public class PingCheck { private static final Logger PingSenderLogger = Logger.getLogger(PingCheck.class); public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); public static BufferedReader serverInput; - + private static int socketTimeOut = 120000; + public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -60,7 +61,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE forward(appName, port, peerID); PingSenderLogger.debug("Forwarded to " + appName + " on " + port); Socket senderSocket = new Socket("127.0.0.1", port); - + senderSocket.setSoTimeout(socketTimeOut); BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); PrintStream output = new PrintStream(senderSocket.getOutputStream()); From 7c6e02ec30e8f652326bef34a8562cd99d432d7d Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 18 Apr 2022 15:45:54 +0530 Subject: [PATCH 116/179] checking token content to get token number Signed-off-by: Nidhin Mahesh A --- .../rubix/TokenTransfer/TokenReceiver.java | 40 +++++++++++++++---- src/com/rubix/TokenTransfer/TokenSender.java | 6 +++ 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index ddd6a364..9f46f172 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -436,16 +436,41 @@ public static String receive() { if (tokenHashTableJSON.has(tokenNumberHash)) { tokenNumber = tokenHashTableJSON.getInt(tokenNumberHash); TokenReceiverLogger.debug("Token Number: " + tokenNumber); + if (tokenNumber > tokenLimitForLevel) { + String errorMessage = "Token Number is greater than Token Limit for the Level"; + output.println("426"); + 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 { - TokenReceiverLogger.debug("token : " + tokenNumberHash + " not found in TokenHashTable"); + TokenReceiverLogger.debug("Invalid Content Found in Token : " + tokenNumberHash); + String errorMessage = "Invalid Content Found in Token"; + output.println("426"); + 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(); } - // if not create new one - - if (tokenChain.length() > 0 || (tokenNumber >= 1204400 && (tokenLevelInt >= 4))) { + if ((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); - JSONObject firstTCObject = tokenChain.getJSONObject(0); TokenReceiverLogger.debug("Last Object = " + lastObject); if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { @@ -475,8 +500,7 @@ public static String receive() { // ! staking checks (1): Check incoming token level - if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) - && firstTCObject.has("QSTHeight")) { + if (ownerCheck && (tokenChain.length() < minumumStakeHeight)) { // && (tokenNumber > 1204400) // ! staking checks (3): Verify the signatures earned during the mining of the @@ -637,7 +661,7 @@ public static String receive() { } } - if (lastObject.has(MiningConstants.STAKED_TOKEN) && tokenChain.length() > 1) { + if (lastObject.has(MiningConstants.STAKED_TOKEN)) { Boolean minedTokenStatus = true; diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 26dccee7..4f4f53c1 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -691,6 +691,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("message", "Token wholly spent already. Kindly re-initiate transaction"); break; + case "426": + TokenSenderLogger.info("Contains tokens invalid for the level. Kindly check tokens in your wallet"); + APIResponse.put("message", + "Contains tokens invalid for the level. Kindly check tokens in your wallet"); + break; + } executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); From ea6265c5d5639058ca51e78f34dce19f9714978c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 18 Apr 2022 16:38:42 +0530 Subject: [PATCH 117/179] fetching level and number hash based on 64 char length Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 9f46f172..cb794615 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -411,8 +411,11 @@ public static String receive() { String tokens = null; JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); String TokenContent = get(wholeTokens.getString(count), ipfs); - String tokenLevel = TokenContent.substring(0, 3); - String tokenNumberHash = TokenContent.substring(3, TokenContent.indexOf("\n")); + String tokenLevel = TokenContent.substring(0, TokenContent.length() - 64); + String tokenNumberHash = TokenContent.substring(TokenContent.length() - 64); + // String tokenLevel = TokenContent.substring(0, 3); + // String tokenNumberHash = TokenContent.substring(3, + // TokenContent.indexOf("\n")); int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLimitForLevel = tokenLimit[tokenLevelInt]; From 5b9c76c09ebbd25700e1b274189aa950462399be Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Mon, 18 Apr 2022 22:53:55 +0530 Subject: [PATCH 118/179] Update file check --- src/com/rubix/Ping/PingCheck.java | 9 +++++---- src/com/rubix/Ping/PingReceive.java | 10 ++++------ src/com/rubix/Resources/Functions.java | 24 ++++++++---------------- 3 files changed, 17 insertions(+), 26 deletions(-) diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index 538388ed..9dea8cef 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -10,25 +10,26 @@ import static com.rubix.Resources.IPFSNetwork.repo; import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; +import io.ipfs.api.IPFS; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.SocketException; - 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 PingCheck { private static final Logger PingSenderLogger = Logger.getLogger(PingCheck.class); public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); public static BufferedReader serverInput; + private static int socketTimeOut = 120000; public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -60,7 +61,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE forward(appName, port, peerID); PingSenderLogger.debug("Forwarded to " + appName + " on " + port); Socket senderSocket = new Socket("127.0.0.1", port); - + senderSocket.setSoTimeout(socketTimeOut); BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); PrintStream output = new PrintStream(senderSocket.getOutputStream()); @@ -82,7 +83,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE return APIResponse; } - if (pongResponse != null && (pongResponse.equals(initHash()))) { + if (pongResponse != null && (pongResponse.equals(getVersion()))) { PingSenderLogger.info("Ping Successful"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index b4a55336..a5e45430 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -3,13 +3,12 @@ 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.getPeerID; -import static com.rubix.Resources.Functions.initHash; -import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.Functions.*; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; +import io.ipfs.api.IPFS; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -17,13 +16,12 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; - 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 PingReceive { public static Logger PingReceiverLogger = Logger.getLogger(PingReceive.class); @@ -78,7 +76,7 @@ public static String receive(int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println(initHash()); + output.println(getVersion()); APIResponse.put("status", "Success"); APIResponse.put("message", "Pong Sent to Sender with Check Sum"); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 935edad9..0b37e4dc 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -9,7 +9,7 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import static com.rubix.Resources.IPFSNetwork.swarmConnectProcess; -import java.awt.image.BufferedImage; +import com.rubix.AuthenticateNode.PropImage; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; @@ -18,7 +18,6 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; -import java.math.RoundingMode; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -26,28 +25,15 @@ import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.imageio.ImageIO; -import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Ping.PingCheck; -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.multiaddr.MultiAddress; public class Functions { @@ -1430,6 +1416,13 @@ public static Double getBalance() throws JSONException { return balance; } + public static String getVersion() { + String CURRENT_VERSION = Version.class.getPackage().getImplementationVersion(); + return CURRENT_VERSION; + } + + + public static String initHash() throws IOException { String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); initPath = initPath.split("\\.jar")[0]; @@ -1600,7 +1593,6 @@ public static boolean checkIPFSStatus(String peerid, IPFS ipfs) { public static boolean ping(String peerid, int port) throws IOException, JSONException { JSONObject pingCheck = PingCheck.Ping(peerid, port); FunctionsLogger.info("Ping Check Response " + pingCheck); - if (pingCheck.getString("status").contains("Failed")) { return false; } else From b47b8c7202386afe6b1fca7a71b6a4a939df99b4 Mon Sep 17 00:00:00 2001 From: Kiran H Date: Tue, 19 Apr 2022 00:28:56 +0530 Subject: [PATCH 119/179] added getVersion in functions.java --- src/com/rubix/Resources/Functions.java | 46 ++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 0b37e4dc..d0c12945 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -10,6 +10,18 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectProcess; import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Ping.PingCheck; + +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.multiaddr.MultiAddress; + +import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; @@ -18,18 +30,25 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; +import java.math.RoundingMode; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; + +import javax.imageio.ImageIO; @@ -1416,9 +1435,30 @@ public static Double getBalance() throws JSONException { return balance; } - public static String getVersion() { - String CURRENT_VERSION = Version.class.getPackage().getImplementationVersion(); - return CURRENT_VERSION; + public static String getVersion(){ + String version = ""; + try { + URL url = new URL("http://localhost:1898/getVersion"); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setRequestProperty("Accept", "application/json"); + if (conn.getResponseCode() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + + conn.getResponseCode()); + } + BufferedReader br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + String output; + while ((output = br.readLine()) != null) { + version = output; + } + conn.disconnect(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return version; } From 712b680fa811a914c3c213b37eb940d2a90eb489 Mon Sep 17 00:00:00 2001 From: Kiran H Date: Tue, 19 Apr 2022 00:51:29 +0530 Subject: [PATCH 120/179] updated selectParts line 239 Tokensender --- src/com/rubix/TokenTransfer/TokenSender.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 4f4f53c1..5efa1836 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -236,7 +236,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } else { Double counter = decimalAmount; - JSONArray selectParts = new JSONArray(partContentArray); + JSONArray selectParts = new JSONArray(partFileContent); while (counter > 0.000D) { counter = formatAmount(counter); TokenSenderLogger.debug("Counter: " + formatAmount(counter)); From 34dda0c58eb1a1749d123b9217e501f2011d2bd4 Mon Sep 17 00:00:00 2001 From: Kiran H Date: Tue, 19 Apr 2022 00:29:12 +0530 Subject: [PATCH 121/179] updated json array while selecting parts --- src/com/rubix/Ping/PingCheck.java | 9 ++++----- src/com/rubix/Ping/PingReceive.java | 10 ++++++---- src/com/rubix/Resources/Functions.java | 20 ++++++++++++++++++++ src/com/rubix/TokenTransfer/TokenSender.java | 2 +- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index 9dea8cef..538388ed 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -10,26 +10,25 @@ import static com.rubix.Resources.IPFSNetwork.repo; import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; -import io.ipfs.api.IPFS; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.SocketException; + 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 PingCheck { private static final Logger PingSenderLogger = Logger.getLogger(PingCheck.class); public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); public static BufferedReader serverInput; - private static int socketTimeOut = 120000; public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -61,7 +60,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE forward(appName, port, peerID); PingSenderLogger.debug("Forwarded to " + appName + " on " + port); Socket senderSocket = new Socket("127.0.0.1", port); - senderSocket.setSoTimeout(socketTimeOut); + BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); PrintStream output = new PrintStream(senderSocket.getOutputStream()); @@ -83,7 +82,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE return APIResponse; } - if (pongResponse != null && (pongResponse.equals(getVersion()))) { + if (pongResponse != null && (pongResponse.equals(initHash()))) { PingSenderLogger.info("Ping Successful"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index a5e45430..b4a55336 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -3,12 +3,13 @@ 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.*; +import static com.rubix.Resources.Functions.getPeerID; +import static com.rubix.Resources.Functions.initHash; +import static com.rubix.Resources.Functions.pathSet; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; -import io.ipfs.api.IPFS; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -16,12 +17,13 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; + 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 PingReceive { public static Logger PingReceiverLogger = Logger.getLogger(PingReceive.class); @@ -76,7 +78,7 @@ public static String receive(int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println(getVersion()); + output.println(initHash()); APIResponse.put("status", "Success"); APIResponse.put("message", "Pong Sent to Sender with Check Sum"); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index d0c12945..368f5cf3 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -9,6 +9,7 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import static com.rubix.Resources.IPFSNetwork.swarmConnectProcess; +<<<<<<< HEAD import com.rubix.AuthenticateNode.PropImage; import com.rubix.Ping.PingCheck; @@ -21,6 +22,8 @@ import io.ipfs.api.IPFS; import io.ipfs.multiaddr.MultiAddress; +======= +>>>>>>> parent of 5b9c76c (Update file check) import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.DataOutputStream; @@ -47,12 +50,25 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; +<<<<<<< HEAD import javax.imageio.ImageIO; +======= +>>>>>>> parent of 5b9c76c (Update file check) +import javax.imageio.ImageIO; +import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Ping.PingCheck; +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.multiaddr.MultiAddress; public class Functions { @@ -1435,6 +1451,7 @@ public static Double getBalance() throws JSONException { return balance; } +<<<<<<< HEAD public static String getVersion(){ String version = ""; try { @@ -1463,6 +1480,8 @@ public static String getVersion(){ +======= +>>>>>>> parent of 5b9c76c (Update file check) public static String initHash() throws IOException { String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); initPath = initPath.split("\\.jar")[0]; @@ -1633,6 +1652,7 @@ public static boolean checkIPFSStatus(String peerid, IPFS ipfs) { public static boolean ping(String peerid, int port) throws IOException, JSONException { JSONObject pingCheck = PingCheck.Ping(peerid, port); FunctionsLogger.info("Ping Check Response " + pingCheck); + if (pingCheck.getString("status").contains("Failed")) { return false; } else diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 26dccee7..fcd7d559 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -236,7 +236,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } else { Double counter = decimalAmount; - JSONArray selectParts = new JSONArray(partContentArray); + JSONArray selectParts = new JSONArray(partFileContent); while (counter > 0.000D) { counter = formatAmount(counter); TokenSenderLogger.debug("Counter: " + formatAmount(counter)); From 6b678d24364d886e96f594a6cf2e30a0fb46b0c3 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Tue, 19 Apr 2022 01:22:49 +0530 Subject: [PATCH 122/179] Revert "updated json array while selecting parts" This reverts commit 34dda0c58eb1a1749d123b9217e501f2011d2bd4. --- src/com/rubix/Ping/PingCheck.java | 9 +++++---- src/com/rubix/Ping/PingReceive.java | 10 ++++------ src/com/rubix/Resources/Functions.java | 20 -------------------- src/com/rubix/TokenTransfer/TokenSender.java | 2 +- 4 files changed, 10 insertions(+), 31 deletions(-) diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index 538388ed..9dea8cef 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -10,25 +10,26 @@ import static com.rubix.Resources.IPFSNetwork.repo; import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; +import io.ipfs.api.IPFS; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.SocketException; - 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 PingCheck { private static final Logger PingSenderLogger = Logger.getLogger(PingCheck.class); public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); public static BufferedReader serverInput; + private static int socketTimeOut = 120000; public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -60,7 +61,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE forward(appName, port, peerID); PingSenderLogger.debug("Forwarded to " + appName + " on " + port); Socket senderSocket = new Socket("127.0.0.1", port); - + senderSocket.setSoTimeout(socketTimeOut); BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); PrintStream output = new PrintStream(senderSocket.getOutputStream()); @@ -82,7 +83,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE return APIResponse; } - if (pongResponse != null && (pongResponse.equals(initHash()))) { + if (pongResponse != null && (pongResponse.equals(getVersion()))) { PingSenderLogger.info("Ping Successful"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index b4a55336..a5e45430 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -3,13 +3,12 @@ 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.getPeerID; -import static com.rubix.Resources.Functions.initHash; -import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.Functions.*; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; +import io.ipfs.api.IPFS; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -17,13 +16,12 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; - 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 PingReceive { public static Logger PingReceiverLogger = Logger.getLogger(PingReceive.class); @@ -78,7 +76,7 @@ public static String receive(int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println(initHash()); + output.println(getVersion()); APIResponse.put("status", "Success"); APIResponse.put("message", "Pong Sent to Sender with Check Sum"); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 368f5cf3..d0c12945 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -9,7 +9,6 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import static com.rubix.Resources.IPFSNetwork.swarmConnectProcess; -<<<<<<< HEAD import com.rubix.AuthenticateNode.PropImage; import com.rubix.Ping.PingCheck; @@ -22,8 +21,6 @@ import io.ipfs.api.IPFS; import io.ipfs.multiaddr.MultiAddress; -======= ->>>>>>> parent of 5b9c76c (Update file check) import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.DataOutputStream; @@ -50,25 +47,12 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; -<<<<<<< HEAD import javax.imageio.ImageIO; -======= ->>>>>>> parent of 5b9c76c (Update file check) -import javax.imageio.ImageIO; -import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Ping.PingCheck; -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.multiaddr.MultiAddress; public class Functions { @@ -1451,7 +1435,6 @@ public static Double getBalance() throws JSONException { return balance; } -<<<<<<< HEAD public static String getVersion(){ String version = ""; try { @@ -1480,8 +1463,6 @@ public static String getVersion(){ -======= ->>>>>>> parent of 5b9c76c (Update file check) public static String initHash() throws IOException { String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); initPath = initPath.split("\\.jar")[0]; @@ -1652,7 +1633,6 @@ public static boolean checkIPFSStatus(String peerid, IPFS ipfs) { public static boolean ping(String peerid, int port) throws IOException, JSONException { JSONObject pingCheck = PingCheck.Ping(peerid, port); FunctionsLogger.info("Ping Check Response " + pingCheck); - if (pingCheck.getString("status").contains("Failed")) { return false; } else diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index fcd7d559..26dccee7 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -236,7 +236,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } else { Double counter = decimalAmount; - JSONArray selectParts = new JSONArray(partFileContent); + JSONArray selectParts = new JSONArray(partContentArray); while (counter > 0.000D) { counter = formatAmount(counter); TokenSenderLogger.debug("Counter: " + formatAmount(counter)); From 5dcebf0d4a8d7510993b07cd884a783c6dbf7476 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Tue, 19 Apr 2022 01:23:04 +0530 Subject: [PATCH 123/179] Revert "added getVersion in functions.java" This reverts commit b47b8c7202386afe6b1fca7a71b6a4a939df99b4. --- src/com/rubix/Resources/Functions.java | 46 ++------------------------ 1 file changed, 3 insertions(+), 43 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index d0c12945..0b37e4dc 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -10,18 +10,6 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectProcess; import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Ping.PingCheck; - -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.multiaddr.MultiAddress; - -import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; @@ -30,25 +18,18 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; -import java.math.RoundingMode; import java.net.HttpURLConnection; -import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Set; - -import javax.imageio.ImageIO; @@ -1435,30 +1416,9 @@ public static Double getBalance() throws JSONException { return balance; } - public static String getVersion(){ - String version = ""; - try { - URL url = new URL("http://localhost:1898/getVersion"); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - conn.setRequestProperty("Accept", "application/json"); - if (conn.getResponseCode() != 200) { - throw new RuntimeException("Failed : HTTP error code : " - + conn.getResponseCode()); - } - BufferedReader br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - String output; - while ((output = br.readLine()) != null) { - version = output; - } - conn.disconnect(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return version; + public static String getVersion() { + String CURRENT_VERSION = Version.class.getPackage().getImplementationVersion(); + return CURRENT_VERSION; } From 3e8557128fe59923b865f2fc0b736279169a5e5f Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Tue, 19 Apr 2022 01:27:39 +0530 Subject: [PATCH 124/179] getVersionUpdate --- src/com/rubix/Ping/PingCheck.java | 2 +- src/com/rubix/Ping/PingReceive.java | 2 +- src/com/rubix/Resources/Functions.java | 33 +++++++++++++++++--- src/com/rubix/TokenTransfer/TokenSender.java | 23 ++++++-------- 4 files changed, 40 insertions(+), 20 deletions(-) diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index 9dea8cef..f418c7c7 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -83,7 +83,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE return APIResponse; } - if (pongResponse != null && (pongResponse.equals(getVersion()))) { + if (pongResponse != null && (pongResponse.equals(initHash()))) { PingSenderLogger.info("Ping Successful"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index a5e45430..622624a5 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -76,7 +76,7 @@ public static String receive(int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println(getVersion()); + output.println(initHash()); APIResponse.put("status", "Success"); APIResponse.put("message", "Pong Sent to Sender with Check Sum"); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 0b37e4dc..99840035 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -35,6 +35,8 @@ + + public class Functions { public static boolean mutex = false; @@ -1416,14 +1418,35 @@ public static Double getBalance() throws JSONException { return balance; } - public static String getVersion() { - String CURRENT_VERSION = Version.class.getPackage().getImplementationVersion(); - return CURRENT_VERSION; + public static String initHash(){ + String version = ""; + try { + URL url = new URL("http://localhost:1898/getVersion"); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setRequestProperty("Accept", "application/json"); + if (conn.getResponseCode() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + + conn.getResponseCode()); + } + BufferedReader br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + String output; + while ((output = br.readLine()) != null) { + version = output; + } + conn.disconnect(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return version; } - public static String initHash() throws IOException { + /*public static String initHash() throws IOException { String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); initPath = initPath.split("\\.jar")[0]; initPath = initPath.split("file:", 2)[1]; @@ -1432,7 +1455,7 @@ public static String initHash() throws IOException { initPath = initPath + ".jar"; String hash = calculateFileHash(initPath, "SHA3-256"); return hash; - } + }*/ public static Double partTokenBalance(String tokenHash) throws JSONException { pathSet(); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 26dccee7..a23e353a 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -38,11 +38,16 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import static com.rubix.Resources.IPFSNetwork.unpin; +import com.rubix.AuthenticateNode.PropImage; +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 java.awt.image.BufferedImage; 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; @@ -50,27 +55,19 @@ 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.imageio.ImageIO; import javax.net.ssl.HttpsURLConnection; - -import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Consensus.InitiatorConsensus; -import com.rubix.Consensus.InitiatorProcedure; -import com.rubix.Resources.Functions; -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 TokenSender { private static final Logger TokenSenderLogger = Logger.getLogger(TokenSender.class); @@ -236,7 +233,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } else { Double counter = decimalAmount; - JSONArray selectParts = new JSONArray(partContentArray); + JSONArray selectParts = new JSONArray(partFileContent); while (counter > 0.000D) { counter = formatAmount(counter); TokenSenderLogger.debug("Counter: " + formatAmount(counter)); From 521b36b6c8975e2a9a535c241601ed2cca1da825 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 19 Apr 2022 14:04:55 +0530 Subject: [PATCH 125/179] hash chain functions Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/com/rubix/Mining/HashChain.java diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java new file mode 100644 index 00000000..97dd7e48 --- /dev/null +++ b/src/com/rubix/Mining/HashChain.java @@ -0,0 +1,34 @@ +package com.rubix.Mining; + +public class HashChain { + + public String newHashChain(String miningTID, String[] DIDs) { + + String finalHash = null; + + do { + + finalHash = calculateHash(miningTID, "SHA3-256"); + + } while (!matchParameter(finalHash, DIDs)); + + return finalHash; + } + + public Boolean verifyHashChain(String tokenTID, String finalHash, String[] DIDs) { + + String calculatedFinalHash = newHashChain(tokenTID, DIDs); + + return calculatedFinalHash == finalHash; + } + + private Boolean matchParameter(String finalHash, String[] DIDs) { + + int MATCH_RULE = 3; + String[] matchSubstrings = new String[DIDs.length + 1]; + + return false; + + } + +} From 61e630741b16f266430a29ab64b8227065949d30 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Tue, 19 Apr 2022 14:30:35 +0530 Subject: [PATCH 126/179] Updated transcation issues --- src/com/rubix/Ping/PingCheck.java | 40 +++++++++++------ src/com/rubix/Ping/PingReceive.java | 16 +++---- src/com/rubix/Ping/QuorumPingReceive.java | 4 +- src/com/rubix/Resources/Functions.java | 47 ++++++++++++++------ src/com/rubix/TokenTransfer/TokenSender.java | 4 +- 5 files changed, 72 insertions(+), 39 deletions(-) diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index f418c7c7..146cbbff 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -1,10 +1,6 @@ package com.rubix.Ping; -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.*; -import static com.rubix.Resources.Functions.nodeData; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.forward; import static com.rubix.Resources.IPFSNetwork.repo; @@ -30,9 +26,11 @@ public class PingCheck { public static BufferedReader serverInput; private static int socketTimeOut = 120000; + public static String currentVersion = initHash(); public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + PingSenderLogger.debug("Current version in PingSender is "+currentVersion); JSONObject APIResponse = new JSONObject(); if (!peerID.equals("")) { @@ -71,6 +69,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE String pongResponse; try { pongResponse = input.readLine(); + PingSenderLogger.debug("Pong received is "+pongResponse); } catch (SocketException e) { PingSenderLogger.warn("Receiver " + receiverDidIpfsHash + " is unable to Respond! - Ping Check"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); @@ -82,19 +81,32 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE return APIResponse; } - - if (pongResponse != null && (pongResponse.equals(initHash()))) { - - PingSenderLogger.info("Ping Successful"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); - output.close(); - input.close(); - senderSocket.close(); - APIResponse.put("status", "Success"); - APIResponse.put("message", "Ping Check Success"); + PingSenderLogger.debug("Pong response after pong received "+pongResponse); + if (pongResponse != null) { + PingSenderLogger.debug("Pong response inside pongRespong not null "+pongResponse); + if(pongResponse.contains(currentVersion)) { + PingSenderLogger.debug("Pong response received is "+ pongResponse); + PingSenderLogger.info("Ping Successful"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Success"); + APIResponse.put("message", "Ping Check Success"); + }else { + PingSenderLogger.debug("Receiver is running "+ pongResponse); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", receiverDidIpfsHash)+ " not running new version"); + } + } else { executeIPFSCommands(" ipfs p2p close -t /p2p/" + peerID); PingSenderLogger.info("Pong response not received"); + PingSenderLogger.info("Pong response now received with error is "+pongResponse); output.close(); input.close(); senderSocket.close(); diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index 622624a5..fdf197dc 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -1,8 +1,5 @@ package com.rubix.Ping; -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.*; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; @@ -28,6 +25,7 @@ public class PingReceive { private static final JSONObject APIResponse = new JSONObject(); private static final IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + public static String currentVersion = initHash(); /** * Receiver Node: To receive a valid token from an authentic sender @@ -40,16 +38,16 @@ public static String receive(int port) throws JSONException { pathSet(); ServerSocket ss; Socket sk; - try { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); - String appName = receiverPeerID.concat("Ping"); + String appName = receiverPeerID.concat(" Ping"); listen(appName, port); ss = new ServerSocket(port); + PingReceiverLogger.debug("Current version in pingreceiver is "+currentVersion); PingReceiverLogger.debug("Ping Receiver Listening on " + port + " appname " + appName); sk = ss.accept(); @@ -76,13 +74,15 @@ public static String receive(int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println(initHash()); - + PingReceiverLogger.debug("Sending version "+currentVersion); + output.println(currentVersion); + PingReceiverLogger.debug("Sent version to pingSender"+currentVersion); APIResponse.put("status", "Success"); APIResponse.put("message", "Pong Sent to Sender with Check Sum"); - PingReceiverLogger.info("Pong Sent"); + PingReceiverLogger.info("Pong Sent "+currentVersion); } else { + PingReceiverLogger.info("Pong Not Sent "); APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong Failed"); PingReceiverLogger.info("Pong Failed"); diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java index 6afaa40a..758be387 100644 --- a/src/com/rubix/Ping/QuorumPingReceive.java +++ b/src/com/rubix/Ping/QuorumPingReceive.java @@ -23,6 +23,7 @@ public class QuorumPingReceive { private static final JSONObject APIResponse = new JSONObject(); private static final IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + public static String currentVersion = initHash(); /** * Receiver Node: To receive a valid token from an authentic sender @@ -72,8 +73,7 @@ public static String receive(int port) throws JSONException { } QuorumPingReceiverLogger.debug("Ping Request Received: " + pingRequest); if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println("Pong"); - + output.println("Pong "+currentVersion); APIResponse.put("status", "Success"); APIResponse.put("message", "Pong Sent"); QuorumPingReceiverLogger.info("Pong Sent"); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 99840035..6784f853 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -10,6 +10,12 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectProcess; import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Ping.PingCheck; + +import io.ipfs.api.IPFS; +import io.ipfs.multiaddr.MultiAddress; + +import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; @@ -18,18 +24,32 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; +import java.math.RoundingMode; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; + +import javax.imageio.ImageIO; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONObject; +import org.json.*; + @@ -1436,6 +1456,7 @@ public static String initHash(){ version = output; } conn.disconnect(); + FunctionsLogger.debug("initHash version is "+version); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { @@ -1538,40 +1559,40 @@ public static void backgroundChecks() { public static String sanityMessage; - public static boolean sanityCheck(String peerid, IPFS ipfs, int port) throws IOException, JSONException { - FunctionsLogger.info("Entering Receiver SanityCheck"); + public static boolean sanityCheck(String userType, String peerid, IPFS ipfs, int port) throws IOException, JSONException { + FunctionsLogger.info("Entering " + userType +" SanityCheck"); boolean sanityCheckErrorFlag = true; if (sanityCheckErrorFlag && checkIPFSStatus(peerid, ipfs)) { - FunctionsLogger.debug("Receiver IPFS is working in " + peerid); - FunctionsLogger.debug("Receiver IPFS check true"); + FunctionsLogger.debug(userType + " IPFS is working in " + peerid); + FunctionsLogger.debug(userType + " IPFS check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Receiver IPFS is not working in " + peerid); - FunctionsLogger.debug("Receiver IPFS check false"); - sanityMessage = "Receiver IPFS is not working in " + peerid; + FunctionsLogger.debug(userType + " IPFS is not working in " + peerid); + FunctionsLogger.debug(userType + " IPFS check false"); + sanityMessage = userType + " IPFS is not working in " + peerid; } if (sanityCheckErrorFlag) { if (bootstrapConnect(peerid, ipfs)) { - FunctionsLogger.debug("Bootstrap connected for Receiver " + peerid); + FunctionsLogger.debug("Bootstrap connected for "+userType +" : " + peerid); FunctionsLogger.debug("Bootstrap check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Bootstrap connection unsuccessful for Receiver " + peerid); + FunctionsLogger.debug("Bootstrap connection unsuccessful for "+userType + " : " + peerid); FunctionsLogger.debug("Bootstrap check false"); - sanityMessage = "Bootstrap connection unsuccessful for Receiver " + peerid; + sanityMessage = "Bootstrap connection unsuccessful for "+userType +" : " + peerid; } } if (sanityCheckErrorFlag) { if (ping(peerid, port)) { - FunctionsLogger.debug("Rceiver is running the latest Jar " + peerid); + FunctionsLogger.debug(userType + " is running the latest Jar :" + peerid); FunctionsLogger.debug("Latest Jar check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Receiver is not running the latest Jar " + peerid); + FunctionsLogger.debug(userType + " is not running the latest Jar :" + peerid); FunctionsLogger.debug("Latest Jar check false"); - sanityMessage = "Receiver is not running the latest Jar. PID: " + peerid; + sanityMessage = userType + " is not running the latest Jar. PID: " + peerid; } } diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index a23e353a..76efa18c 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -111,7 +111,7 @@ 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); - boolean sanityCheck = sanityCheck(receiverPeerId, ipfs, port + 10); + boolean sanityCheck = sanityCheck("Receiver",receiverPeerId, ipfs, port + 10); if (!sanityCheck) { APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); @@ -428,7 +428,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception for (int i = 0; i < quorumArray.length(); i++) { String quorumPeerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", quorumArray.getString(i)); - boolean quorumSanityCheck = sanityCheck(quorumPeerID, ipfs, port + 11); + boolean quorumSanityCheck = sanityCheck("Quorum",quorumPeerID, ipfs, port + 11); if (!quorumSanityCheck) { sanityFailedQuorum.put(quorumPeerID); From 1c6ea0fb1244dfe8e255522d75026b57840e6a0f Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 20 Apr 2022 11:01:31 +0530 Subject: [PATCH 127/179] hashchain iteration Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 30 +++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 97dd7e48..3023a29f 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -1,17 +1,24 @@ package com.rubix.Mining; +import com.rubix.Resources.Functions; + public class HashChain { + String finalHash = ""; + public String newHashChain(String miningTID, String[] DIDs) { - String finalHash = null; + String finalHash = miningTID; + int iterCount = 0; do { - finalHash = calculateHash(miningTID, "SHA3-256"); + iterCount++; + finalHash = Functions.calculateHash(finalHash, "SHA3-256"); - } while (!matchParameter(finalHash, DIDs)); + } while (!matchParameter(DIDs)); + System.out.println("Hash Chain Iteration Count: " + iterCount); return finalHash; } @@ -22,12 +29,23 @@ public Boolean verifyHashChain(String tokenTID, String finalHash, String[] DIDs) return calculatedFinalHash == finalHash; } - private Boolean matchParameter(String finalHash, String[] DIDs) { + private Boolean matchParameter(String[] DIDs) { int MATCH_RULE = 3; String[] matchSubstrings = new String[DIDs.length + 1]; - - return false; + for (int i = 0; i < DIDs.length; i++) { + matchSubstrings[i] = DIDs[i].substring(DIDs[i].length() - MATCH_RULE, DIDs[i].length()); + } + matchSubstrings[-1] = finalHash.substring(finalHash.length() - MATCH_RULE, finalHash.length()); + + // check if all the strings in the array are the same + for (int i = 0; i < matchSubstrings.length - 1; i++) { + if (!matchSubstrings[i].equals(matchSubstrings[i + 1])) { + return false; + } + } + + return true; } From 22ae9d4d011111fe49e53aecd75a7dd68602e560 Mon Sep 17 00:00:00 2001 From: Kiran H Date: Wed, 20 Apr 2022 11:25:24 +0530 Subject: [PATCH 128/179] updated java standards in HashChain class --- src/com/rubix/Mining/HashChain.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 3023a29f..607a1100 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -4,9 +4,9 @@ public class HashChain { - String finalHash = ""; + private static String finalHash = ""; - public String newHashChain(String miningTID, String[] DIDs) { + public static String newHashChain(String miningTID, String[] DIDs) { String finalHash = miningTID; int iterCount = 0; @@ -22,14 +22,14 @@ public String newHashChain(String miningTID, String[] DIDs) { return finalHash; } - public Boolean verifyHashChain(String tokenTID, String finalHash, String[] DIDs) { + public static Boolean verifyHashChain(String tokenTID, String finalHash, String[] DIDs) { String calculatedFinalHash = newHashChain(tokenTID, DIDs); return calculatedFinalHash == finalHash; } - private Boolean matchParameter(String[] DIDs) { + private static Boolean matchParameter(String[] DIDs) { int MATCH_RULE = 3; String[] matchSubstrings = new String[DIDs.length + 1]; From 94f2b983b1dd234aca34a5d8bb05d916b59c4dee Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 20 Apr 2022 13:21:34 +0530 Subject: [PATCH 129/179] + logger Signed-off-by: Nidhin Mahesh A --- .gitignore | 8 ++++++++ src/com/rubix/Mining/HashChain.java | 12 ++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 6f86d28b..5e400714 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,11 @@ tests/thunder-tests/thunderActivity.db tests/thunder-tests/thunderclient.db tests/thunder-tests/thunderCollection.db tests/thunder-tests/thunderEnvironment.db +tests/thunder-tests/thunderActivity.json +tests/thunder-tests/thunderclient.json +tests/thunder-tests/thunderCollection.json +tests/thunder-tests/thunderEnvironment.json +tests/thunder-tests/backup/thunderActivity.db +tests/thunder-tests/backup/thunderclient.db +tests/thunder-tests/backup/thunderCollection.db +tests/thunder-tests/backup/thunderEnvironment.db diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 607a1100..68c634f0 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -2,14 +2,18 @@ import com.rubix.Resources.Functions; +import org.apache.log4j.Logger; + public class HashChain { + public static Logger HashChainLogger = Logger.getLogger(HashChain.class); + private static String finalHash = ""; + private static int iterCount = 0; public static String newHashChain(String miningTID, String[] DIDs) { - String finalHash = miningTID; - int iterCount = 0; + finalHash = miningTID; do { @@ -18,7 +22,7 @@ public static String newHashChain(String miningTID, String[] DIDs) { } while (!matchParameter(DIDs)); - System.out.println("Hash Chain Iteration Count: " + iterCount); + HashChainLogger.trace("Hash Chain Length for TID: " + miningTID + " is = " + iterCount); return finalHash; } @@ -30,7 +34,7 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ } private static Boolean matchParameter(String[] DIDs) { - + HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); int MATCH_RULE = 3; String[] matchSubstrings = new String[DIDs.length + 1]; for (int i = 0; i < DIDs.length; i++) { From c6dab72c9267e9a2527f75ca88cf0d0376ac02d4 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 20 Apr 2022 13:55:00 +0530 Subject: [PATCH 130/179] substring array size fix Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 68c634f0..8a84b183 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -40,7 +40,7 @@ private static Boolean matchParameter(String[] DIDs) { for (int i = 0; i < DIDs.length; i++) { matchSubstrings[i] = DIDs[i].substring(DIDs[i].length() - MATCH_RULE, DIDs[i].length()); } - matchSubstrings[-1] = finalHash.substring(finalHash.length() - MATCH_RULE, finalHash.length()); + matchSubstrings[DIDs.length + 1] = finalHash.substring(finalHash.length() - MATCH_RULE, finalHash.length()); // check if all the strings in the array are the same for (int i = 0; i < matchSubstrings.length - 1; i++) { From e22672476a9dfda9dbcb492a045c4e83eef9ab90 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Wed, 20 Apr 2022 14:32:11 +0530 Subject: [PATCH 131/179] fix array error to match strings Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 8a84b183..9dccd531 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -36,19 +36,13 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ private static Boolean matchParameter(String[] DIDs) { HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); int MATCH_RULE = 3; - String[] matchSubstrings = new String[DIDs.length + 1]; - for (int i = 0; i < DIDs.length; i++) { - matchSubstrings[i] = DIDs[i].substring(DIDs[i].length() - MATCH_RULE, DIDs[i].length()); - } - matchSubstrings[DIDs.length + 1] = finalHash.substring(finalHash.length() - MATCH_RULE, finalHash.length()); - // check if all the strings in the array are the same - for (int i = 0; i < matchSubstrings.length - 1; i++) { - if (!matchSubstrings[i].equals(matchSubstrings[i + 1])) { - return false; + for (int i = 0; i < DIDs.length; i++) { + if (finalHash.substring(finalHash.length() - MATCH_RULE) + .equals(DIDs[i].substring(DIDs[i].length() - MATCH_RULE))) { + return true; } } - return true; } From 199a81849dd74ddea7a8ccf22ae3264d06e0cead Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 21 Apr 2022 01:26:06 +0530 Subject: [PATCH 132/179] fix boolean error Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 9dccd531..eb55c586 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -20,7 +20,7 @@ public static String newHashChain(String miningTID, String[] DIDs) { iterCount++; finalHash = Functions.calculateHash(finalHash, "SHA3-256"); - } while (!matchParameter(DIDs)); + } while (ruleNotMatch(DIDs)); HashChainLogger.trace("Hash Chain Length for TID: " + miningTID + " is = " + iterCount); return finalHash; @@ -33,17 +33,17 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ return calculatedFinalHash == finalHash; } - private static Boolean matchParameter(String[] DIDs) { + private static Boolean ruleNotMatch(String[] DIDs) { HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); int MATCH_RULE = 3; for (int i = 0; i < DIDs.length; i++) { - if (finalHash.substring(finalHash.length() - MATCH_RULE) - .equals(DIDs[i].substring(DIDs[i].length() - MATCH_RULE))) { + if (!(finalHash.substring(finalHash.length() - MATCH_RULE) + .equals(DIDs[i].substring(DIDs[i].length() - MATCH_RULE)))) { return true; } } - return true; + return false; } From b7996b62191bc92963bcaa2c0b32793df0723dfc Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 21 Apr 2022 13:23:04 +0530 Subject: [PATCH 133/179] change match rule from 3 to 1 Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index eb55c586..badf6a02 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -35,7 +35,7 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ private static Boolean ruleNotMatch(String[] DIDs) { HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); - int MATCH_RULE = 3; + int MATCH_RULE = 1; for (int i = 0; i < DIDs.length; i++) { if (!(finalHash.substring(finalHash.length() - MATCH_RULE) From e16a6cc8885aff7fe4b08b69939d195e9844f791 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Thu, 21 Apr 2022 18:50:31 +0530 Subject: [PATCH 134/179] Updated for Kappa 62.1.7 --- src/com/rubix/Ping/PingReceive.java | 87 ++++++++++--- src/com/rubix/Ping/QuorumPingReceive.java | 142 ---------------------- 2 files changed, 67 insertions(+), 162 deletions(-) delete mode 100644 src/com/rubix/Ping/QuorumPingReceive.java diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index fdf197dc..3a315414 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -5,20 +5,18 @@ import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; -import io.ipfs.api.IPFS; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; +import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; + 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 PingReceive { public static Logger PingReceiverLogger = Logger.getLogger(PingReceive.class); @@ -34,32 +32,33 @@ public class PingReceive { * @throws IOException handles IO Exceptions * @throws JSONException handles JSON Exceptions */ - public static String receive(int port) throws JSONException { + public static String receive(String userType,int port) throws JSONException { pathSet(); ServerSocket ss; Socket sk; + try { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); - String appName = receiverPeerID.concat(" Ping"); + String appName = receiverPeerID.concat("Ping"); listen(appName, port); ss = new ServerSocket(port); - PingReceiverLogger.debug("Current version in pingreceiver is "+currentVersion); - PingReceiverLogger.debug("Ping Receiver Listening on " + port + " appname " + appName); + PingReceiverLogger.debug("Ping "+userType+" Listening on " + port + " appname " + appName); sk = ss.accept(); PingReceiverLogger.debug("Data Incoming..."); BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintStream output = new PrintStream(sk.getOutputStream()); + int height = 0; String pingRequest; try { pingRequest = input.readLine(); } catch (SocketException e) { - PingReceiverLogger.warn("Sender Stream Null - PingCheck"); + PingReceiverLogger.warn("Sender Stream Null - PingCheck"); APIResponse.put("did", ""); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); @@ -73,19 +72,67 @@ public static String receive(int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); - if (pingRequest != null && pingRequest.contains("PingCheck")) { - PingReceiverLogger.debug("Sending version "+currentVersion); - output.println(currentVersion); - PingReceiverLogger.debug("Sent version to pingSender"+currentVersion); + if (pingRequest != null) { + if(pingRequest.contains("PingCheck")) { + PingReceiverLogger.debug(userType + " Sending version "+currentVersion); + output.println(currentVersion); + PingReceiverLogger.debug(userType + " Sent version to pingSender"+currentVersion); + APIResponse.put("status", "Success"); + APIResponse.put("message", "Pong Sent to Sender with Check Sum"); + PingReceiverLogger.info(userType + " Pong Sent "+currentVersion); + + } + else + if(pingRequest.contains("Get-TokenChain-Height")) { + String tokenHash; + try { + tokenHash = input.readLine(); + } catch (SocketException e) { + PingReceiverLogger.warn("Sender Stream Null - tokenHash"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - tokenHash"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + if (tokenHash != null && tokenHash.startsWith("Qm") && tokenHash.length() == 46) { + PingReceiverLogger.info("Token chain height requested for: " + tokenHash); + File tokenChainFile = new File(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + if(!tokenChainFile.exists()) { + PingReceiverLogger.info("Token chain file not found"); + height = 0; + } + else{ + String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + JSONArray chainArray = new JSONArray(tokenChain); + height = chainArray.length()-1; + PingReceiverLogger.info("Chain height: " + height); + } + } + + } + else{ + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Request Failed"); + PingReceiverLogger.info(userType+ " Request Failed"); + } + APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent to Sender with Check Sum"); - PingReceiverLogger.info("Pong Sent "+currentVersion); + APIResponse.put("message", "Pong Sent"); + PingReceiverLogger.info(userType + " Pong Sent"); - } else { - PingReceiverLogger.info("Pong Not Sent "); + } + else { + PingReceiverLogger.info("Pong Not Sent "); APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong Failed"); - PingReceiverLogger.info("Pong Failed"); + PingReceiverLogger.info(userType + " Pong Failed"); } executeIPFSCommands(" ipfs p2p close -t /p2p/" + pingRequest); output.close(); diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java deleted file mode 100644 index 758be387..00000000 --- a/src/com/rubix/Ping/QuorumPingReceive.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.rubix.Ping; - -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; -import static com.rubix.Resources.IPFSNetwork.listen; -import static com.rubix.Resources.IPFSNetwork.repo; - -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketException; - -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 QuorumPingReceive { - public static Logger QuorumPingReceiverLogger = Logger.getLogger(QuorumPingReceive.class); - - private static final JSONObject APIResponse = new JSONObject(); - private static final IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); - public static String currentVersion = initHash(); - - /** - * Receiver Node: To receive a valid token from an authentic sender - * - * @return Transaction Details (JSONObject) - * @throws IOException handles IO Exceptions - * @throws JSONException handles JSON Exceptions - */ - public static String receive(int port) throws JSONException { - pathSet(); - ServerSocket ss; - Socket sk; - - try { - repo(ipfs); - - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - - String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); - String appName = receiverPeerID.concat("Ping"); - listen(appName, port); - ss = new ServerSocket(port); - QuorumPingReceiverLogger.debug("Ping Quorum Listening on " + port + " appname " + appName); - - sk = ss.accept(); - QuorumPingReceiverLogger.debug("Data Incoming..."); - BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); - PrintStream output = new PrintStream(sk.getOutputStream()); - - int height = 0; - String pingRequest; - try { - pingRequest = input.readLine(); - } catch (SocketException e) { - QuorumPingReceiverLogger.warn("Sender Stream Null - PingCheck"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - PingCheck"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - QuorumPingReceiverLogger.debug("Ping Request Received: " + pingRequest); - if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println("Pong "+currentVersion); - APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent"); - QuorumPingReceiverLogger.info("Pong Sent"); - - } - else if (pingRequest != null && pingRequest.contains("Get-TokenChain-Height")) { - String tokenHash; - try { - tokenHash = input.readLine(); - } catch (SocketException e) { - QuorumPingReceiverLogger.warn("Sender Stream Null - tokenHash"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - tokenHash"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - if (tokenHash != null && tokenHash.startsWith("Qm") && tokenHash.length() == 46) { - QuorumPingReceiverLogger.info("Token chain height requested for: " + tokenHash); - File tokenChainFile = new File(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); - if(!tokenChainFile.exists()) { - QuorumPingReceiverLogger.info("Token chain file not found"); - height = 0; - } - else{ - String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); - JSONArray chainArray = new JSONArray(tokenChain); - height = chainArray.length()-1; - QuorumPingReceiverLogger.info("Chain height: " + height); - } - } - else{ - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Request Failed"); - QuorumPingReceiverLogger.info("Request Failed"); - } - output.println(height); - - APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent"); - QuorumPingReceiverLogger.info("Pong Sent"); - - } - else { - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Pong Failed"); - QuorumPingReceiverLogger.info("Pong Failed"); - } - executeIPFSCommands(" ipfs p2p close -t /p2p/" + pingRequest); - output.close(); - input.close(); - sk.close(); - ss.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - return APIResponse.toString(); - } -} From 847dc65b25446dc2634c238d440f5023a13f8324 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Thu, 21 Apr 2022 19:01:17 +0530 Subject: [PATCH 135/179] Revert "Merge branch 'mining-pledge-updateVersionCheck' of https://github.com/rubixchain/rubixcorejava into mining-pledge-updateVersionCheck" This reverts commit 707551ee4f82f1f40eff4e2ada9ce719c5ebec99, reversing changes made to e16a6cc8885aff7fe4b08b69939d195e9844f791. --- src/com/rubix/Mining/HashChain.java | 34 -- src/com/rubix/Ping/PingCheck.java | 1 - .../rubix/TokenTransfer/TokenReceiver.java | 540 ++++++++---------- src/com/rubix/TokenTransfer/TokenSender.java | 6 - 4 files changed, 240 insertions(+), 341 deletions(-) delete mode 100644 src/com/rubix/Mining/HashChain.java diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java deleted file mode 100644 index 97dd7e48..00000000 --- a/src/com/rubix/Mining/HashChain.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.rubix.Mining; - -public class HashChain { - - public String newHashChain(String miningTID, String[] DIDs) { - - String finalHash = null; - - do { - - finalHash = calculateHash(miningTID, "SHA3-256"); - - } while (!matchParameter(finalHash, DIDs)); - - return finalHash; - } - - public Boolean verifyHashChain(String tokenTID, String finalHash, String[] DIDs) { - - String calculatedFinalHash = newHashChain(tokenTID, DIDs); - - return calculatedFinalHash == finalHash; - } - - private Boolean matchParameter(String finalHash, String[] DIDs) { - - int MATCH_RULE = 3; - String[] matchSubstrings = new String[DIDs.length + 1]; - - return false; - - } - -} diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index d7a25b67..146cbbff 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -27,7 +27,6 @@ public class PingCheck { private static int socketTimeOut = 120000; public static String currentVersion = initHash(); - public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index cb794615..9e3bda50 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -75,10 +75,6 @@ public class TokenReceiver { private static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); private static String SenWalletBin; - // token limit for each level - private static final int[] tokenLimit = { 0, 5000000, 2425000, 2303750, 2188563, 2079134, 1975178, 1876419, 1782598, - 1693468, 1608795, 1528355, 1451937, 1379340 }; - /** * Receiver Node: To receive a valid token from an authentic sender * @@ -410,339 +406,283 @@ public static String receive() { String tokens = null; JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); - String TokenContent = get(wholeTokens.getString(count), ipfs); - String tokenLevel = TokenContent.substring(0, TokenContent.length() - 64); - String tokenNumberHash = TokenContent.substring(TokenContent.length() - 64); - // String tokenLevel = TokenContent.substring(0, 3); - // String tokenNumberHash = TokenContent.substring(3, - // TokenContent.indexOf("\n")); - - int tokenLevelInt = Integer.parseInt(tokenLevel); - int tokenLimitForLevel = tokenLimit[tokenLevelInt]; - int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); - int minumumStakeHeight = tokenLevelValue * 4; - int tokenNumber = 1204401; - - // check TokenHashTable exists - File tokenHashTable = new File( - WALLET_DATA_PATH.concat("TokenHashTable").concat(".json")); - if (!tokenHashTable.exists()) { - tokenHashTable.createNewFile(); - JSONObject tokenHashTableJSON = new JSONObject(); - for (int i = 1; i <= 5000000; i++) { - tokenHashTableJSON.put(calculateHash(String.valueOf(i), "SHA-256"), i); - } - writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); - } - String tokenHashTableData = readFile(tokenHashTable.toString()); - JSONObject tokenHashTableJSON = new JSONObject(tokenHashTableData); - if (tokenHashTableJSON.has(tokenNumberHash)) { - tokenNumber = tokenHashTableJSON.getInt(tokenNumberHash); - TokenReceiverLogger.debug("Token Number: " + tokenNumber); - if (tokenNumber > tokenLimitForLevel) { - String errorMessage = "Token Number is greater than Token Limit for the Level"; - output.println("426"); - 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(); + JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); + JSONObject firstTCObject = tokenChain.getJSONObject(0); + TokenReceiverLogger.debug("Last Object = " + lastObject); + + if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { + + TokenReceiverLogger.debug("Checking ownership"); + String owner = lastObject.getString("owner"); + tokens = allTokens.getString(count); + String hashString = tokens.concat(senderDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); + String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here Sender Calculation"); + TokenReceiverLogger.debug("tokens: " + tokens); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); + + if (!owner.equals(ownerRecalculated)) { + ownerCheck = false; + invalidTokens.put(tokens); } - } else { - TokenReceiverLogger.debug("Invalid Content Found in Token : " + tokenNumberHash); - String errorMessage = "Invalid Content Found in Token"; - output.println("426"); - 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(); - } - - if ((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { - - JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); - TokenReceiverLogger.debug("Last Object = " + lastObject); - if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { - - TokenReceiverLogger.debug("Checking ownership"); - String owner = lastObject.getString("owner"); - tokens = allTokens.getString(count); - String hashString = tokens.concat(senderDidIpfsHash); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); - String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + // ! staking checks (1..4) starts here + + // ! staking checks (1): Check incoming token level + String TokenContent = get(wholeTokens.getString(count), ipfs); + String tokenLevel = TokenContent.substring(0, 3); + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + int minumumStakeHeight = tokenLevelValue * 4; + int tokenNumber = 1204400; + + if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) + && firstTCObject.has("QSTHeight")) { + // && (tokenNumber > 1204400) + + // ! staking checks (3): Verify the signatures earned during the mining of the + // ! incoming mint token + JSONObject genesiObject = tokenChain.getJSONObject(0); + JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); + + int randomNumber = new Random().nextInt(15); + JSONObject genesisSignaturesContent = genesiObject + .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); + Iterator randomKey = genesisSignaturesContent.keys(); + for (int i = 0; i < randomNumber; i++) { + randomKey.next(); + } + /** String randomKeyString = randomKey.next().toString(); + JSONObject verificationPick = new JSONObject(); + verificationPick.put("did", randomKeyString); + verificationPick.put("hash", genesiObject.getString("tid")); + verificationPick.put("signature", genesisSignaturesContent.getString(randomKeyString)); - TokenReceiverLogger.debug("Ownership Here Sender Calculation"); - TokenReceiverLogger.debug("tokens: " + tokens); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); + if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) { - if (!owner.equals(ownerRecalculated)) { + if (Authenticate.verifySignature(verificationPick.toString())) { + TokenReceiverLogger.debug("Staking check (3) successful"); + } else { + TokenReceiverLogger.debug( + "Staking check (3) failed: Could not verify genesis credit signature"); + ownerCheck = false; + invalidTokens.put(tokens); + } + } else { + TokenReceiverLogger.debug( + "Staking check (3) failed: Genesis TID is not equal to the hash of the genesis signature"); ownerCheck = false; invalidTokens.put(tokens); } + */ + // else { + // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not + // found"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } - // ! staking checks (1..4) starts here - - // ! staking checks (1): Check incoming token level - - if (ownerCheck && (tokenChain.length() < minumumStakeHeight)) { - // && (tokenNumber > 1204400) - - // ! staking checks (3): Verify the signatures earned during the mining of the - // ! incoming mint token - JSONObject genesiObject = tokenChain.getJSONObject(0); - JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); - - int randomNumber = new Random().nextInt(15); - JSONObject genesisSignaturesContent = genesiObject - .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); - Iterator randomKey = genesisSignaturesContent.keys(); - for (int i = 0; i < randomNumber; i++) { - randomKey.next(); - } - /** - * String randomKeyString = randomKey.next().toString(); - * JSONObject verificationPick = new JSONObject(); - * verificationPick.put("did", randomKeyString); - * verificationPick.put("hash", genesiObject.getString("tid")); - * verificationPick.put("signature", - * genesisSignaturesContent.getString(randomKeyString)); - * - * if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) - * { - * - * if (Authenticate.verifySignature(verificationPick.toString())) { - * TokenReceiverLogger.debug("Staking check (3) successful"); - * } else { - * TokenReceiverLogger.debug( - * "Staking check (3) failed: Could not verify genesis credit signature"); - * ownerCheck = false; - * invalidTokens.put(tokens); - * } - * } else { - * TokenReceiverLogger.debug( - * "Staking check (3) failed: Genesis TID is not equal to the hash of the - * genesis signature"); - * ownerCheck = false; - * invalidTokens.put(tokens); - * } - */ - // else { - // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not - // found"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - - // ! staking checks (2): For incoming new mint token, verify the staked token - - if (stakeDataArray.length() == 3) { - - JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); - JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); - JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); - - String[] stakedTokenTC = new String[3]; - String[] stakedTokenSignTC = new String[3]; - String[] stakerDIDTC = new String[3]; - String[] mineIDTC = new String[3]; - String[] mineIDSignTC = new String[3]; - - stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); - mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); - mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); - mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); - - for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { - - String mineIDContent = get(mineIDTC[stakeCount], ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - TokenReceiverLogger.debug(mineIDContentJSON.toString()); - - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - - String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); - String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); - String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); - - TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); - - TokenReceiverLogger.debug(stakerDIDMineData); - TokenReceiverLogger.debug(stakedTokenMineData); - TokenReceiverLogger.debug(stakedTokenSignMineData); - - if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) - && stakedTokenTC[stakeCount].equals(stakedTokenMineData) - && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakerDIDTC[stakeCount]); - detailsToVerify.put("hash", mineIDTC[stakeCount]); - detailsToVerify.put("signature", mineIDSignTC[stakeCount]); - if (Authenticate.verifySignature(detailsToVerify.toString())) { - - boolean minedTokenStatus = true; - ArrayList ownersArray = IPFSNetwork - .dhtOwnerCheck(stakedTokenTC[stakeCount]); - for (int i = 0; i < ownersArray.size(); i++) { - if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { - minedTokenStatus = false; - } - } - if (!minedTokenStatus) { - TokenReceiverLogger.debug( - "Staked token is not found with staker DID: " - + stakerDIDTC[stakeCount]); - ownerCheck = false; - invalidTokens.put(tokens); + // ! staking checks (2): For incoming new mint token, verify the staked token + + if(stakeDataArray.length() == 3) { + + JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); + JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); + JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); + + String[] stakedTokenTC = new String[3]; + String[] stakedTokenSignTC = new String[3]; + String[] stakerDIDTC = new String[3]; + String[] mineIDTC = new String[3]; + String[] mineIDSignTC = new String[3]; + + stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); + mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); + mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); + mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); + + for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { + + String mineIDContent = get(mineIDTC[stakeCount], ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + TokenReceiverLogger.debug(mineIDContentJSON.toString()); + + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); + + String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); + String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); + String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); + + TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); + + TokenReceiverLogger.debug(stakerDIDMineData); + TokenReceiverLogger.debug(stakedTokenMineData); + TokenReceiverLogger.debug(stakedTokenSignMineData); + + if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) + && stakedTokenTC[stakeCount].equals(stakedTokenMineData) + && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakerDIDTC[stakeCount]); + detailsToVerify.put("hash", mineIDTC[stakeCount]); + detailsToVerify.put("signature", mineIDSignTC[stakeCount]); + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + boolean minedTokenStatus = true; + ArrayList ownersArray = IPFSNetwork + .dhtOwnerCheck(stakedTokenTC[stakeCount]); + for (int i = 0; i < ownersArray.size(); i++) { + if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { + minedTokenStatus = false; } - - } else { + } + if (!minedTokenStatus) { TokenReceiverLogger.debug( - "Staking check (2) failed - unable to verify mine ID signature by staker: " + "Staked token is not found with staker DID: " + stakerDIDTC[stakeCount]); ownerCheck = false; invalidTokens.put(tokens); } - TokenReceiverLogger - .debug("MineID Verification Successful with Staking node: " - + stakerDIDTC[stakeCount]); } else { - TokenReceiverLogger.debug("Staking check (2) failed"); + TokenReceiverLogger.debug( + "Staking check (2) failed - unable to verify mine ID signature by staker: " + + stakerDIDTC[stakeCount]); ownerCheck = false; invalidTokens.put(tokens); } - TokenReceiverLogger.debug("Staking check (2) successful"); - // } else { - // TokenReceiverLogger.debug( - // "Staking check (2) failed: Could not verify mine ID signature"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } + TokenReceiverLogger + .debug("MineID Verification Successful with Staking node: " + + stakerDIDTC[stakeCount]); + } else { + TokenReceiverLogger.debug("Staking check (2) failed"); + ownerCheck = false; + invalidTokens.put(tokens); } - } else { - ownerCheck = false; - TokenReceiverLogger.debug("Staked Token is not available!"); - + TokenReceiverLogger.debug("Staking check (2) successful"); + // } else { + // TokenReceiverLogger.debug( + // "Staking check (2) failed: Could not verify mine ID signature"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } } - + + }else { + ownerCheck = false; + TokenReceiverLogger.debug("Staked Token is not available!"); + } + + } - if (lastObject.has(MiningConstants.STAKED_TOKEN)) { + } + if (lastObject.has(MiningConstants.STAKED_TOKEN) && tokenChain.length() > 1) { - Boolean minedTokenStatus = true; + Boolean minedTokenStatus = true; - String mineID = lastObject.getString(MINE_ID); + String mineID = lastObject.getString(MINE_ID); - String mineIDContent = get(mineID, ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + String mineIDContent = get(mineID, ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakeData.getString(STAKED_TOKEN)); - for (int i = 0; i < ownersArray.size(); i++) { - if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - stakeData.getString( - STAKED_TOKEN), - mineIDContentJSON.getString("tokenContent"))) { - minedTokenStatus = false; - } + ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakeData.getString(STAKED_TOKEN)); + for (int i = 0; i < ownersArray.size(); i++) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + stakeData.getString( + STAKED_TOKEN), + mineIDContentJSON.getString("tokenContent"))) { + minedTokenStatus = false; } - if (!minedTokenStatus) { - TokenReceiverLogger - .debug("Staking check failed: Found staked token but token height < 46"); - ownerCheck = false; - invalidTokens.put(tokens); - } - - TokenReceiverLogger.debug( - "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); + } + if (!minedTokenStatus) { + TokenReceiverLogger + .debug("Staking check failed: Found staked token but token height < 46"); ownerCheck = false; invalidTokens.put(tokens); + } - // JSONObject tokenToVerify = new JSONObject(); - // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { - - // JSONObject stakeData = - // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); - // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); - // String stakedToken = stakeData.getString(STAKED_TOKEN); - // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); - - // tokenToVerify.put("did", senderDidIpfsHash); - // tokenToVerify.put("hash", stakedToken); - // tokenToVerify.put("signature", stakedTokenSign); - - // if (Authenticate.verifySignature(tokenToVerify.toString())) { - - // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); - // for (int i = 0; i < ownersArray.size(); i++) { - // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - // mineIDContentJSON.getString("tokenContent"))) { - // minedTokenStatus = false; - // } - // } - // if (!minedTokenStatus) { - // TokenReceiverLogger - // .debug("Staking check failed: Found staked token but token height < 46"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - - // TokenReceiverLogger.debug( - // "Staking check failed: Found staked token but unable to transfer while mined - // token height is not satisfied for the network"); - // ownerCheck = false; - // invalidTokens.put(tokens); + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); + ownerCheck = false; + invalidTokens.put(tokens); + + // JSONObject tokenToVerify = new JSONObject(); + // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { + + // JSONObject stakeData = + // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); + // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); + // String stakedToken = stakeData.getString(STAKED_TOKEN); + // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); + + // tokenToVerify.put("did", senderDidIpfsHash); + // tokenToVerify.put("hash", stakedToken); + // tokenToVerify.put("signature", stakedTokenSign); + + // if (Authenticate.verifySignature(tokenToVerify.toString())) { + + // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + // for (int i = 0; i < ownersArray.size(); i++) { + // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + // mineIDContentJSON.getString("tokenContent"))) { + // minedTokenStatus = false; + // } + // } + // if (!minedTokenStatus) { + // TokenReceiverLogger + // .debug("Staking check failed: Found staked token but token height < 46"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to transfer while mined + // token height is not satisfied for the network"); + // ownerCheck = false; + // invalidTokens.put(tokens); + + // } else { + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to verify staked token + // height"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + // } - // } else { - // TokenReceiverLogger.debug( - // "Staking check failed: Found staked token but unable to verify staked token - // height"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - // } - - } } + // ! staking checks ends here } + + if (!ownerCheck) { TokenReceiverLogger.debug("Ownership Check Failed"); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index bfb4b194..76efa18c 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -688,12 +688,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("message", "Token wholly spent already. Kindly re-initiate transaction"); break; - case "426": - TokenSenderLogger.info("Contains tokens invalid for the level. Kindly check tokens in your wallet"); - APIResponse.put("message", - "Contains tokens invalid for the level. Kindly check tokens in your wallet"); - break; - } executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); From 9967b50d2178fea7b504fd7791f05919d06878fd Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 22 Apr 2022 11:02:52 +0530 Subject: [PATCH 136/179] match only one DID instead of 3 staked DIDs Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index badf6a02..d6e5a954 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -38,13 +38,13 @@ private static Boolean ruleNotMatch(String[] DIDs) { int MATCH_RULE = 1; for (int i = 0; i < DIDs.length; i++) { - if (!(finalHash.substring(finalHash.length() - MATCH_RULE) - .equals(DIDs[i].substring(DIDs[i].length() - MATCH_RULE)))) { - return true; + if (finalHash.substring(finalHash.length() - MATCH_RULE) + .equals(DIDs[i].substring(DIDs[i].length() - MATCH_RULE))) { + HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); + return false; } } return false; - } } From 9aef7054b386a84762622cc2bd99127074ebcb9b Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 22 Apr 2022 12:30:53 +0530 Subject: [PATCH 137/179] update logic Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index d6e5a954..ad85d289 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -35,16 +35,15 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ private static Boolean ruleNotMatch(String[] DIDs) { HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); - int MATCH_RULE = 1; + int MATCH_RULE = 3; for (int i = 0; i < DIDs.length; i++) { if (finalHash.substring(finalHash.length() - MATCH_RULE) .equals(DIDs[i].substring(DIDs[i].length() - MATCH_RULE))) { - HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); return false; } } - return false; + return true; } } From fb84d4ade65302dd26ec67938fa43e3cf0e5d913 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 28 Apr 2022 11:13:11 +0530 Subject: [PATCH 138/179] iter hashchain rule Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index ad85d289..538ad96c 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -35,7 +35,7 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ private static Boolean ruleNotMatch(String[] DIDs) { HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); - int MATCH_RULE = 3; + int MATCH_RULE = 1; for (int i = 0; i < DIDs.length; i++) { if (finalHash.substring(finalHash.length() - MATCH_RULE) From 01be836c4f17742867cf7afd814bb0f221d06e6c Mon Sep 17 00:00:00 2001 From: Gokul P S <94040889+gklps@users.noreply.github.com> Date: Thu, 28 Apr 2022 11:43:33 +0530 Subject: [PATCH 139/179] Add files via upload --- src/com/rubix/Mining/HashChain.java | 49 +++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/com/rubix/Mining/HashChain.java diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java new file mode 100644 index 00000000..538ad96c --- /dev/null +++ b/src/com/rubix/Mining/HashChain.java @@ -0,0 +1,49 @@ +package com.rubix.Mining; + +import com.rubix.Resources.Functions; + +import org.apache.log4j.Logger; + +public class HashChain { + + public static Logger HashChainLogger = Logger.getLogger(HashChain.class); + + private static String finalHash = ""; + private static int iterCount = 0; + + public static String newHashChain(String miningTID, String[] DIDs) { + + finalHash = miningTID; + + do { + + iterCount++; + finalHash = Functions.calculateHash(finalHash, "SHA3-256"); + + } while (ruleNotMatch(DIDs)); + + HashChainLogger.trace("Hash Chain Length for TID: " + miningTID + " is = " + iterCount); + return finalHash; + } + + public static Boolean verifyHashChain(String tokenTID, String finalHash, String[] DIDs) { + + String calculatedFinalHash = newHashChain(tokenTID, DIDs); + + return calculatedFinalHash == finalHash; + } + + private static Boolean ruleNotMatch(String[] DIDs) { + HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); + int MATCH_RULE = 1; + + for (int i = 0; i < DIDs.length; i++) { + if (finalHash.substring(finalHash.length() - MATCH_RULE) + .equals(DIDs[i].substring(DIDs[i].length() - MATCH_RULE))) { + return false; + } + } + return true; + } + +} From cc190416ab99a9a38d0e18571ea876f4e7b3ef11 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Thu, 28 Apr 2022 11:46:23 +0530 Subject: [PATCH 140/179] adding pom --- .gitignore | 5 +++++ pom.xml | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 pom.xml diff --git a/.gitignore b/.gitignore index 5e400714..ed976ac6 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,8 @@ tests/thunder-tests/backup/thunderActivity.db tests/thunder-tests/backup/thunderclient.db tests/thunder-tests/backup/thunderCollection.db tests/thunder-tests/backup/thunderEnvironment.db +/target/ +.classpath +.project +.settings/org.eclipse.jdt.core.prefs +java-rubix-core.iml diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..3ba08dd7 --- /dev/null +++ b/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + com.rubix.core + Kappa + 5000 + + src + + + src + + **/*.java + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 11 + 11 + + + + + + + com.did.core + did + provided + + + + + + com.did.core + did + 8.6 + + + + \ No newline at end of file From 5845b509599effd7cfe379e5bf5076244ed960b4 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Thu, 28 Apr 2022 11:47:57 +0530 Subject: [PATCH 141/179] Revert "adding pom" This reverts commit cc190416ab99a9a38d0e18571ea876f4e7b3ef11. --- .gitignore | 5 ----- pom.xml | 43 ------------------------------------------- 2 files changed, 48 deletions(-) delete mode 100644 pom.xml diff --git a/.gitignore b/.gitignore index ed976ac6..5e400714 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,3 @@ tests/thunder-tests/backup/thunderActivity.db tests/thunder-tests/backup/thunderclient.db tests/thunder-tests/backup/thunderCollection.db tests/thunder-tests/backup/thunderEnvironment.db -/target/ -.classpath -.project -.settings/org.eclipse.jdt.core.prefs -java-rubix-core.iml diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 3ba08dd7..00000000 --- a/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - 4.0.0 - com.rubix.core - Kappa - 5000 - - src - - - src - - **/*.java - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 11 - 11 - - - - - - - com.did.core - did - provided - - - - - - com.did.core - did - 8.6 - - - - \ No newline at end of file From eb941c8e49e4cb67a975a176cb103e26b2f0f627 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Thu, 28 Apr 2022 11:50:22 +0530 Subject: [PATCH 142/179] Revert "Revert "adding pom"" This reverts commit 5845b509599effd7cfe379e5bf5076244ed960b4. --- .gitignore | 5 +++++ pom.xml | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 pom.xml diff --git a/.gitignore b/.gitignore index 5e400714..ed976ac6 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,8 @@ tests/thunder-tests/backup/thunderActivity.db tests/thunder-tests/backup/thunderclient.db tests/thunder-tests/backup/thunderCollection.db tests/thunder-tests/backup/thunderEnvironment.db +/target/ +.classpath +.project +.settings/org.eclipse.jdt.core.prefs +java-rubix-core.iml diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..3ba08dd7 --- /dev/null +++ b/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + com.rubix.core + Kappa + 5000 + + src + + + src + + **/*.java + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 11 + 11 + + + + + + + com.did.core + did + provided + + + + + + com.did.core + did + 8.6 + + + + \ No newline at end of file From af48553a76edac5e3ea73737beea248b4c4826d7 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Thu, 28 Apr 2022 13:39:51 +0530 Subject: [PATCH 143/179] Revert "Merge pull request #27 from rubixchain/mining-pledge-updateVersionCheck" This reverts commit d508d00e707b75cfe8df1925031f2fb3b9da07ed, reversing changes made to fb84d4ade65302dd26ec67938fa43e3cf0e5d913. --- src/com/rubix/Ping/PingCheck.java | 1 + src/com/rubix/Ping/PingReceive.java | 87 +-- src/com/rubix/Ping/QuorumPingReceive.java | 142 +++++ .../rubix/TokenTransfer/TokenReceiver.java | 540 ++++++++++-------- src/com/rubix/TokenTransfer/TokenSender.java | 6 + 5 files changed, 469 insertions(+), 307 deletions(-) create mode 100644 src/com/rubix/Ping/QuorumPingReceive.java diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index 146cbbff..d7a25b67 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -27,6 +27,7 @@ public class PingCheck { private static int socketTimeOut = 120000; public static String currentVersion = initHash(); + public static JSONObject Ping(String peerID, int port) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index 3a315414..fdf197dc 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -5,18 +5,20 @@ import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; -import java.io.*; +import io.ipfs.api.IPFS; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; - 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 PingReceive { public static Logger PingReceiverLogger = Logger.getLogger(PingReceive.class); @@ -32,33 +34,32 @@ public class PingReceive { * @throws IOException handles IO Exceptions * @throws JSONException handles JSON Exceptions */ - public static String receive(String userType,int port) throws JSONException { + public static String receive(int port) throws JSONException { pathSet(); ServerSocket ss; Socket sk; - try { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); - String appName = receiverPeerID.concat("Ping"); + String appName = receiverPeerID.concat(" Ping"); listen(appName, port); ss = new ServerSocket(port); - PingReceiverLogger.debug("Ping "+userType+" Listening on " + port + " appname " + appName); + PingReceiverLogger.debug("Current version in pingreceiver is "+currentVersion); + PingReceiverLogger.debug("Ping Receiver Listening on " + port + " appname " + appName); sk = ss.accept(); PingReceiverLogger.debug("Data Incoming..."); BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintStream output = new PrintStream(sk.getOutputStream()); - int height = 0; String pingRequest; try { pingRequest = input.readLine(); } catch (SocketException e) { - PingReceiverLogger.warn("Sender Stream Null - PingCheck"); + PingReceiverLogger.warn("Sender Stream Null - PingCheck"); APIResponse.put("did", ""); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); @@ -72,67 +73,19 @@ public static String receive(String userType,int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); - if (pingRequest != null) { - if(pingRequest.contains("PingCheck")) { - PingReceiverLogger.debug(userType + " Sending version "+currentVersion); - output.println(currentVersion); - PingReceiverLogger.debug(userType + " Sent version to pingSender"+currentVersion); - APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent to Sender with Check Sum"); - PingReceiverLogger.info(userType + " Pong Sent "+currentVersion); - - } - else - if(pingRequest.contains("Get-TokenChain-Height")) { - String tokenHash; - try { - tokenHash = input.readLine(); - } catch (SocketException e) { - PingReceiverLogger.warn("Sender Stream Null - tokenHash"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - tokenHash"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - if (tokenHash != null && tokenHash.startsWith("Qm") && tokenHash.length() == 46) { - PingReceiverLogger.info("Token chain height requested for: " + tokenHash); - File tokenChainFile = new File(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); - if(!tokenChainFile.exists()) { - PingReceiverLogger.info("Token chain file not found"); - height = 0; - } - else{ - String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); - JSONArray chainArray = new JSONArray(tokenChain); - height = chainArray.length()-1; - PingReceiverLogger.info("Chain height: " + height); - } - } - - } - else{ - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Request Failed"); - PingReceiverLogger.info(userType+ " Request Failed"); - } - + if (pingRequest != null && pingRequest.contains("PingCheck")) { + PingReceiverLogger.debug("Sending version "+currentVersion); + output.println(currentVersion); + PingReceiverLogger.debug("Sent version to pingSender"+currentVersion); APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent"); - PingReceiverLogger.info(userType + " Pong Sent"); + APIResponse.put("message", "Pong Sent to Sender with Check Sum"); + PingReceiverLogger.info("Pong Sent "+currentVersion); - } - else { - PingReceiverLogger.info("Pong Not Sent "); + } else { + PingReceiverLogger.info("Pong Not Sent "); APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong Failed"); - PingReceiverLogger.info(userType + " Pong Failed"); + PingReceiverLogger.info("Pong Failed"); } executeIPFSCommands(" ipfs p2p close -t /p2p/" + pingRequest); output.close(); diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java new file mode 100644 index 00000000..758be387 --- /dev/null +++ b/src/com/rubix/Ping/QuorumPingReceive.java @@ -0,0 +1,142 @@ +package com.rubix.Ping; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.Resources.IPFSNetwork.listen; +import static com.rubix.Resources.IPFSNetwork.repo; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; + +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 QuorumPingReceive { + public static Logger QuorumPingReceiverLogger = Logger.getLogger(QuorumPingReceive.class); + + private static final JSONObject APIResponse = new JSONObject(); + private static final IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + public static String currentVersion = initHash(); + + /** + * Receiver Node: To receive a valid token from an authentic sender + * + * @return Transaction Details (JSONObject) + * @throws IOException handles IO Exceptions + * @throws JSONException handles JSON Exceptions + */ + public static String receive(int port) throws JSONException { + pathSet(); + ServerSocket ss; + Socket sk; + + try { + repo(ipfs); + + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); + String appName = receiverPeerID.concat("Ping"); + listen(appName, port); + ss = new ServerSocket(port); + QuorumPingReceiverLogger.debug("Ping Quorum Listening on " + port + " appname " + appName); + + sk = ss.accept(); + QuorumPingReceiverLogger.debug("Data Incoming..."); + BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); + PrintStream output = new PrintStream(sk.getOutputStream()); + + int height = 0; + String pingRequest; + try { + pingRequest = input.readLine(); + } catch (SocketException e) { + QuorumPingReceiverLogger.warn("Sender Stream Null - PingCheck"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - PingCheck"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + QuorumPingReceiverLogger.debug("Ping Request Received: " + pingRequest); + if (pingRequest != null && pingRequest.contains("PingCheck")) { + output.println("Pong "+currentVersion); + APIResponse.put("status", "Success"); + APIResponse.put("message", "Pong Sent"); + QuorumPingReceiverLogger.info("Pong Sent"); + + } + else if (pingRequest != null && pingRequest.contains("Get-TokenChain-Height")) { + String tokenHash; + try { + tokenHash = input.readLine(); + } catch (SocketException e) { + QuorumPingReceiverLogger.warn("Sender Stream Null - tokenHash"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - tokenHash"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + if (tokenHash != null && tokenHash.startsWith("Qm") && tokenHash.length() == 46) { + QuorumPingReceiverLogger.info("Token chain height requested for: " + tokenHash); + File tokenChainFile = new File(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + if(!tokenChainFile.exists()) { + QuorumPingReceiverLogger.info("Token chain file not found"); + height = 0; + } + else{ + String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + JSONArray chainArray = new JSONArray(tokenChain); + height = chainArray.length()-1; + QuorumPingReceiverLogger.info("Chain height: " + height); + } + } + else{ + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Request Failed"); + QuorumPingReceiverLogger.info("Request Failed"); + } + output.println(height); + + APIResponse.put("status", "Success"); + APIResponse.put("message", "Pong Sent"); + QuorumPingReceiverLogger.info("Pong Sent"); + + } + else { + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Pong Failed"); + QuorumPingReceiverLogger.info("Pong Failed"); + } + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pingRequest); + output.close(); + input.close(); + sk.close(); + ss.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + return APIResponse.toString(); + } +} diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 9e3bda50..cb794615 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -75,6 +75,10 @@ public class TokenReceiver { private static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); private static String SenWalletBin; + // token limit for each level + private static final int[] tokenLimit = { 0, 5000000, 2425000, 2303750, 2188563, 2079134, 1975178, 1876419, 1782598, + 1693468, 1608795, 1528355, 1451937, 1379340 }; + /** * Receiver Node: To receive a valid token from an authentic sender * @@ -406,283 +410,339 @@ public static String receive() { String tokens = null; JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); - JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); - JSONObject firstTCObject = tokenChain.getJSONObject(0); - TokenReceiverLogger.debug("Last Object = " + lastObject); - - if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { - - TokenReceiverLogger.debug("Checking ownership"); - String owner = lastObject.getString("owner"); - tokens = allTokens.getString(count); - String hashString = tokens.concat(senderDidIpfsHash); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); - String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); - - TokenReceiverLogger.debug("Ownership Here Sender Calculation"); - TokenReceiverLogger.debug("tokens: " + tokens); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); - - if (!owner.equals(ownerRecalculated)) { - ownerCheck = false; - invalidTokens.put(tokens); + String TokenContent = get(wholeTokens.getString(count), ipfs); + String tokenLevel = TokenContent.substring(0, TokenContent.length() - 64); + String tokenNumberHash = TokenContent.substring(TokenContent.length() - 64); + // String tokenLevel = TokenContent.substring(0, 3); + // String tokenNumberHash = TokenContent.substring(3, + // TokenContent.indexOf("\n")); + + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLimitForLevel = tokenLimit[tokenLevelInt]; + int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + int minumumStakeHeight = tokenLevelValue * 4; + int tokenNumber = 1204401; + + // check TokenHashTable exists + File tokenHashTable = new File( + WALLET_DATA_PATH.concat("TokenHashTable").concat(".json")); + if (!tokenHashTable.exists()) { + tokenHashTable.createNewFile(); + JSONObject tokenHashTableJSON = new JSONObject(); + for (int i = 1; i <= 5000000; i++) { + tokenHashTableJSON.put(calculateHash(String.valueOf(i), "SHA-256"), i); } + writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); + } + String tokenHashTableData = readFile(tokenHashTable.toString()); + JSONObject tokenHashTableJSON = new JSONObject(tokenHashTableData); + if (tokenHashTableJSON.has(tokenNumberHash)) { + tokenNumber = tokenHashTableJSON.getInt(tokenNumberHash); + TokenReceiverLogger.debug("Token Number: " + tokenNumber); + if (tokenNumber > tokenLimitForLevel) { + String errorMessage = "Token Number is greater than Token Limit for the Level"; + output.println("426"); + 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 { + TokenReceiverLogger.debug("Invalid Content Found in Token : " + tokenNumberHash); + String errorMessage = "Invalid Content Found in Token"; + output.println("426"); + 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(); + } - // ! staking checks (1..4) starts here - - // ! staking checks (1): Check incoming token level - String TokenContent = get(wholeTokens.getString(count), ipfs); - String tokenLevel = TokenContent.substring(0, 3); - int tokenLevelInt = Integer.parseInt(tokenLevel); - int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); - int minumumStakeHeight = tokenLevelValue * 4; - int tokenNumber = 1204400; - - if (ownerCheck && (tokenChain.length() < minumumStakeHeight) && (tokenLevelInt >= 4) - && firstTCObject.has("QSTHeight")) { - // && (tokenNumber > 1204400) - - // ! staking checks (3): Verify the signatures earned during the mining of the - // ! incoming mint token - JSONObject genesiObject = tokenChain.getJSONObject(0); - JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); - - int randomNumber = new Random().nextInt(15); - JSONObject genesisSignaturesContent = genesiObject - .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); - Iterator randomKey = genesisSignaturesContent.keys(); - for (int i = 0; i < randomNumber; i++) { - randomKey.next(); - } - /** String randomKeyString = randomKey.next().toString(); - JSONObject verificationPick = new JSONObject(); - verificationPick.put("did", randomKeyString); - verificationPick.put("hash", genesiObject.getString("tid")); - verificationPick.put("signature", genesisSignaturesContent.getString(randomKeyString)); + if ((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { - if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) { + JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); + TokenReceiverLogger.debug("Last Object = " + lastObject); - if (Authenticate.verifySignature(verificationPick.toString())) { - TokenReceiverLogger.debug("Staking check (3) successful"); - } else { - TokenReceiverLogger.debug( - "Staking check (3) failed: Could not verify genesis credit signature"); - ownerCheck = false; - invalidTokens.put(tokens); - } - } else { - TokenReceiverLogger.debug( - "Staking check (3) failed: Genesis TID is not equal to the hash of the genesis signature"); + if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { + + TokenReceiverLogger.debug("Checking ownership"); + String owner = lastObject.getString("owner"); + tokens = allTokens.getString(count); + String hashString = tokens.concat(senderDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); + String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here Sender Calculation"); + TokenReceiverLogger.debug("tokens: " + tokens); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); + + if (!owner.equals(ownerRecalculated)) { ownerCheck = false; invalidTokens.put(tokens); } - */ - // else { - // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not - // found"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - // ! staking checks (2): For incoming new mint token, verify the staked token - - if(stakeDataArray.length() == 3) { - - JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); - JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); - JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); - - String[] stakedTokenTC = new String[3]; - String[] stakedTokenSignTC = new String[3]; - String[] stakerDIDTC = new String[3]; - String[] mineIDTC = new String[3]; - String[] mineIDSignTC = new String[3]; - - stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); - mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); - mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); - mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); - - for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { - - String mineIDContent = get(mineIDTC[stakeCount], ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - TokenReceiverLogger.debug(mineIDContentJSON.toString()); - - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - - String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); - String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); - String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); - - TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); - - TokenReceiverLogger.debug(stakerDIDMineData); - TokenReceiverLogger.debug(stakedTokenMineData); - TokenReceiverLogger.debug(stakedTokenSignMineData); - - if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) - && stakedTokenTC[stakeCount].equals(stakedTokenMineData) - && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakerDIDTC[stakeCount]); - detailsToVerify.put("hash", mineIDTC[stakeCount]); - detailsToVerify.put("signature", mineIDSignTC[stakeCount]); - if (Authenticate.verifySignature(detailsToVerify.toString())) { - - boolean minedTokenStatus = true; - ArrayList ownersArray = IPFSNetwork - .dhtOwnerCheck(stakedTokenTC[stakeCount]); - for (int i = 0; i < ownersArray.size(); i++) { - if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { - minedTokenStatus = false; + // ! staking checks (1..4) starts here + + // ! staking checks (1): Check incoming token level + + if (ownerCheck && (tokenChain.length() < minumumStakeHeight)) { + // && (tokenNumber > 1204400) + + // ! staking checks (3): Verify the signatures earned during the mining of the + // ! incoming mint token + JSONObject genesiObject = tokenChain.getJSONObject(0); + JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); + + int randomNumber = new Random().nextInt(15); + JSONObject genesisSignaturesContent = genesiObject + .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); + Iterator randomKey = genesisSignaturesContent.keys(); + for (int i = 0; i < randomNumber; i++) { + randomKey.next(); + } + /** + * String randomKeyString = randomKey.next().toString(); + * JSONObject verificationPick = new JSONObject(); + * verificationPick.put("did", randomKeyString); + * verificationPick.put("hash", genesiObject.getString("tid")); + * verificationPick.put("signature", + * genesisSignaturesContent.getString(randomKeyString)); + * + * if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) + * { + * + * if (Authenticate.verifySignature(verificationPick.toString())) { + * TokenReceiverLogger.debug("Staking check (3) successful"); + * } else { + * TokenReceiverLogger.debug( + * "Staking check (3) failed: Could not verify genesis credit signature"); + * ownerCheck = false; + * invalidTokens.put(tokens); + * } + * } else { + * TokenReceiverLogger.debug( + * "Staking check (3) failed: Genesis TID is not equal to the hash of the + * genesis signature"); + * ownerCheck = false; + * invalidTokens.put(tokens); + * } + */ + // else { + // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not + // found"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + + // ! staking checks (2): For incoming new mint token, verify the staked token + + if (stakeDataArray.length() == 3) { + + JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); + JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); + JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); + + String[] stakedTokenTC = new String[3]; + String[] stakedTokenSignTC = new String[3]; + String[] stakerDIDTC = new String[3]; + String[] mineIDTC = new String[3]; + String[] mineIDSignTC = new String[3]; + + stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); + mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); + mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); + + stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); + stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); + stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); + mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); + mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); + + for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { + + String mineIDContent = get(mineIDTC[stakeCount], ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + TokenReceiverLogger.debug(mineIDContentJSON.toString()); + + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); + + String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); + String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); + String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); + + TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); + + TokenReceiverLogger.debug(stakerDIDMineData); + TokenReceiverLogger.debug(stakedTokenMineData); + TokenReceiverLogger.debug(stakedTokenSignMineData); + + if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) + && stakedTokenTC[stakeCount].equals(stakedTokenMineData) + && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakerDIDTC[stakeCount]); + detailsToVerify.put("hash", mineIDTC[stakeCount]); + detailsToVerify.put("signature", mineIDSignTC[stakeCount]); + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + boolean minedTokenStatus = true; + ArrayList ownersArray = IPFSNetwork + .dhtOwnerCheck(stakedTokenTC[stakeCount]); + for (int i = 0; i < ownersArray.size(); i++) { + if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { + minedTokenStatus = false; + } } - } - if (!minedTokenStatus) { + if (!minedTokenStatus) { + TokenReceiverLogger.debug( + "Staked token is not found with staker DID: " + + stakerDIDTC[stakeCount]); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { TokenReceiverLogger.debug( - "Staked token is not found with staker DID: " + "Staking check (2) failed - unable to verify mine ID signature by staker: " + stakerDIDTC[stakeCount]); ownerCheck = false; invalidTokens.put(tokens); } - } else { - TokenReceiverLogger.debug( - "Staking check (2) failed - unable to verify mine ID signature by staker: " + TokenReceiverLogger + .debug("MineID Verification Successful with Staking node: " + stakerDIDTC[stakeCount]); + } else { + TokenReceiverLogger.debug("Staking check (2) failed"); ownerCheck = false; invalidTokens.put(tokens); } - TokenReceiverLogger - .debug("MineID Verification Successful with Staking node: " - + stakerDIDTC[stakeCount]); - } else { - TokenReceiverLogger.debug("Staking check (2) failed"); - ownerCheck = false; - invalidTokens.put(tokens); + TokenReceiverLogger.debug("Staking check (2) successful"); + // } else { + // TokenReceiverLogger.debug( + // "Staking check (2) failed: Could not verify mine ID signature"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } } - TokenReceiverLogger.debug("Staking check (2) successful"); - // } else { - // TokenReceiverLogger.debug( - // "Staking check (2) failed: Could not verify mine ID signature"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } + } else { + ownerCheck = false; + TokenReceiverLogger.debug("Staked Token is not available!"); + } - - }else { - ownerCheck = false; - TokenReceiverLogger.debug("Staked Token is not available!"); - - } - + } } - } - if (lastObject.has(MiningConstants.STAKED_TOKEN) && tokenChain.length() > 1) { + if (lastObject.has(MiningConstants.STAKED_TOKEN)) { - Boolean minedTokenStatus = true; + Boolean minedTokenStatus = true; - String mineID = lastObject.getString(MINE_ID); + String mineID = lastObject.getString(MINE_ID); - String mineIDContent = get(mineID, ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + String mineIDContent = get(mineID, ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); + JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakeData.getString(STAKED_TOKEN)); - for (int i = 0; i < ownersArray.size(); i++) { - if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - stakeData.getString( - STAKED_TOKEN), - mineIDContentJSON.getString("tokenContent"))) { - minedTokenStatus = false; + ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakeData.getString(STAKED_TOKEN)); + for (int i = 0; i < ownersArray.size(); i++) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + stakeData.getString( + STAKED_TOKEN), + mineIDContentJSON.getString("tokenContent"))) { + minedTokenStatus = false; + } } - } - if (!minedTokenStatus) { - TokenReceiverLogger - .debug("Staking check failed: Found staked token but token height < 46"); + if (!minedTokenStatus) { + TokenReceiverLogger + .debug("Staking check failed: Found staked token but token height < 46"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); ownerCheck = false; invalidTokens.put(tokens); - } - TokenReceiverLogger.debug( - "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); - ownerCheck = false; - invalidTokens.put(tokens); - - // JSONObject tokenToVerify = new JSONObject(); - // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { - - // JSONObject stakeData = - // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); - // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); - // String stakedToken = stakeData.getString(STAKED_TOKEN); - // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); - - // tokenToVerify.put("did", senderDidIpfsHash); - // tokenToVerify.put("hash", stakedToken); - // tokenToVerify.put("signature", stakedTokenSign); - - // if (Authenticate.verifySignature(tokenToVerify.toString())) { - - // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); - // for (int i = 0; i < ownersArray.size(); i++) { - // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - // mineIDContentJSON.getString("tokenContent"))) { - // minedTokenStatus = false; - // } - // } - // if (!minedTokenStatus) { - // TokenReceiverLogger - // .debug("Staking check failed: Found staked token but token height < 46"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - - // TokenReceiverLogger.debug( - // "Staking check failed: Found staked token but unable to transfer while mined - // token height is not satisfied for the network"); - // ownerCheck = false; - // invalidTokens.put(tokens); - - // } else { - // TokenReceiverLogger.debug( - // "Staking check failed: Found staked token but unable to verify staked token - // height"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - // } + // JSONObject tokenToVerify = new JSONObject(); + // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { + // JSONObject stakeData = + // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); + // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); + // String stakedToken = stakeData.getString(STAKED_TOKEN); + // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); + + // tokenToVerify.put("did", senderDidIpfsHash); + // tokenToVerify.put("hash", stakedToken); + // tokenToVerify.put("signature", stakedTokenSign); + + // if (Authenticate.verifySignature(tokenToVerify.toString())) { + + // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + // for (int i = 0; i < ownersArray.size(); i++) { + // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + // mineIDContentJSON.getString("tokenContent"))) { + // minedTokenStatus = false; + // } + // } + // if (!minedTokenStatus) { + // TokenReceiverLogger + // .debug("Staking check failed: Found staked token but token height < 46"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to transfer while mined + // token height is not satisfied for the network"); + // ownerCheck = false; + // invalidTokens.put(tokens); + + // } else { + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to verify staked token + // height"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + // } + + } } - // ! staking checks ends here } - - if (!ownerCheck) { TokenReceiverLogger.debug("Ownership Check Failed"); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 76efa18c..bfb4b194 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -688,6 +688,12 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("message", "Token wholly spent already. Kindly re-initiate transaction"); break; + case "426": + TokenSenderLogger.info("Contains tokens invalid for the level. Kindly check tokens in your wallet"); + APIResponse.put("message", + "Contains tokens invalid for the level. Kindly check tokens in your wallet"); + break; + } executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); From 10755788c5218c4f95d4a6ade3fbb2210c91944c Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Thu, 28 Apr 2022 13:50:27 +0530 Subject: [PATCH 144/179] Mining Pledge to include updated PingCheck --- src/com/rubix/Ping/PingReceive.java | 88 +++++++++++--- src/com/rubix/Ping/QuorumPingReceive.java | 142 ---------------------- 2 files changed, 73 insertions(+), 157 deletions(-) delete mode 100644 src/com/rubix/Ping/QuorumPingReceive.java diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index fdf197dc..43f28818 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -1,12 +1,20 @@ package com.rubix.Ping; -import static com.rubix.Resources.Functions.*; +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.TOKENCHAIN_PATH; +import static com.rubix.Resources.Functions.getPeerID; +import static com.rubix.Resources.Functions.initHash; +import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.Functions.readFile; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; import static com.rubix.Resources.IPFSNetwork.listen; import static com.rubix.Resources.IPFSNetwork.repo; import io.ipfs.api.IPFS; import java.io.BufferedReader; +import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; @@ -15,6 +23,7 @@ import java.net.SocketException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -34,32 +43,33 @@ public class PingReceive { * @throws IOException handles IO Exceptions * @throws JSONException handles JSON Exceptions */ - public static String receive(int port) throws JSONException { + public static String receive(String userType,int port) throws JSONException { pathSet(); ServerSocket ss; Socket sk; + try { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); - String appName = receiverPeerID.concat(" Ping"); + String appName = receiverPeerID.concat("Ping"); listen(appName, port); ss = new ServerSocket(port); - PingReceiverLogger.debug("Current version in pingreceiver is "+currentVersion); - PingReceiverLogger.debug("Ping Receiver Listening on " + port + " appname " + appName); + PingReceiverLogger.debug("Ping "+userType+" Listening on " + port + " appname " + appName); sk = ss.accept(); PingReceiverLogger.debug("Data Incoming..."); BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintStream output = new PrintStream(sk.getOutputStream()); + int height = 0; String pingRequest; try { pingRequest = input.readLine(); } catch (SocketException e) { - PingReceiverLogger.warn("Sender Stream Null - PingCheck"); + PingReceiverLogger.warn("Sender Stream Null - PingCheck"); APIResponse.put("did", ""); APIResponse.put("tid", "null"); APIResponse.put("status", "Failed"); @@ -73,19 +83,67 @@ public static String receive(int port) throws JSONException { } PingReceiverLogger.debug("Ping Request Received: " + pingRequest); - if (pingRequest != null && pingRequest.contains("PingCheck")) { - PingReceiverLogger.debug("Sending version "+currentVersion); - output.println(currentVersion); - PingReceiverLogger.debug("Sent version to pingSender"+currentVersion); + if (pingRequest != null) { + if(pingRequest.contains("PingCheck")) { + PingReceiverLogger.debug(userType + " Sending version "+currentVersion); + output.println(currentVersion); + PingReceiverLogger.debug(userType + " Sent version to pingSender"+currentVersion); + APIResponse.put("status", "Success"); + APIResponse.put("message", "Pong Sent to Sender with Check Sum"); + PingReceiverLogger.info(userType + " Pong Sent "+currentVersion); + + } + else + if(pingRequest.contains("Get-TokenChain-Height")) { + String tokenHash; + try { + tokenHash = input.readLine(); + } catch (SocketException e) { + PingReceiverLogger.warn("Sender Stream Null - tokenHash"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - tokenHash"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + if (tokenHash != null && tokenHash.startsWith("Qm") && tokenHash.length() == 46) { + PingReceiverLogger.info("Token chain height requested for: " + tokenHash); + File tokenChainFile = new File(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + if(!tokenChainFile.exists()) { + PingReceiverLogger.info("Token chain file not found"); + height = 0; + } + else{ + String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + JSONArray chainArray = new JSONArray(tokenChain); + height = chainArray.length()-1; + PingReceiverLogger.info("Chain height: " + height); + } + } + + } + else{ + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Request Failed"); + PingReceiverLogger.info(userType+ " Request Failed"); + } + APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent to Sender with Check Sum"); - PingReceiverLogger.info("Pong Sent "+currentVersion); + APIResponse.put("message", "Pong Sent"); + PingReceiverLogger.info(userType + " Pong Sent"); - } else { - PingReceiverLogger.info("Pong Not Sent "); + } + else { + PingReceiverLogger.info("Pong Not Sent "); APIResponse.put("status", "Failed"); APIResponse.put("message", "Pong Failed"); - PingReceiverLogger.info("Pong Failed"); + PingReceiverLogger.info(userType + " Pong Failed"); } executeIPFSCommands(" ipfs p2p close -t /p2p/" + pingRequest); output.close(); diff --git a/src/com/rubix/Ping/QuorumPingReceive.java b/src/com/rubix/Ping/QuorumPingReceive.java deleted file mode 100644 index 758be387..00000000 --- a/src/com/rubix/Ping/QuorumPingReceive.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.rubix.Ping; - -import static com.rubix.Resources.Functions.*; -import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; -import static com.rubix.Resources.IPFSNetwork.listen; -import static com.rubix.Resources.IPFSNetwork.repo; - -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketException; - -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 QuorumPingReceive { - public static Logger QuorumPingReceiverLogger = Logger.getLogger(QuorumPingReceive.class); - - private static final JSONObject APIResponse = new JSONObject(); - private static final IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); - public static String currentVersion = initHash(); - - /** - * Receiver Node: To receive a valid token from an authentic sender - * - * @return Transaction Details (JSONObject) - * @throws IOException handles IO Exceptions - * @throws JSONException handles JSON Exceptions - */ - public static String receive(int port) throws JSONException { - pathSet(); - ServerSocket ss; - Socket sk; - - try { - repo(ipfs); - - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - - String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); - String appName = receiverPeerID.concat("Ping"); - listen(appName, port); - ss = new ServerSocket(port); - QuorumPingReceiverLogger.debug("Ping Quorum Listening on " + port + " appname " + appName); - - sk = ss.accept(); - QuorumPingReceiverLogger.debug("Data Incoming..."); - BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); - PrintStream output = new PrintStream(sk.getOutputStream()); - - int height = 0; - String pingRequest; - try { - pingRequest = input.readLine(); - } catch (SocketException e) { - QuorumPingReceiverLogger.warn("Sender Stream Null - PingCheck"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - PingCheck"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - QuorumPingReceiverLogger.debug("Ping Request Received: " + pingRequest); - if (pingRequest != null && pingRequest.contains("PingCheck")) { - output.println("Pong "+currentVersion); - APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent"); - QuorumPingReceiverLogger.info("Pong Sent"); - - } - else if (pingRequest != null && pingRequest.contains("Get-TokenChain-Height")) { - String tokenHash; - try { - tokenHash = input.readLine(); - } catch (SocketException e) { - QuorumPingReceiverLogger.warn("Sender Stream Null - tokenHash"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - tokenHash"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - if (tokenHash != null && tokenHash.startsWith("Qm") && tokenHash.length() == 46) { - QuorumPingReceiverLogger.info("Token chain height requested for: " + tokenHash); - File tokenChainFile = new File(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); - if(!tokenChainFile.exists()) { - QuorumPingReceiverLogger.info("Token chain file not found"); - height = 0; - } - else{ - String tokenChain = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); - JSONArray chainArray = new JSONArray(tokenChain); - height = chainArray.length()-1; - QuorumPingReceiverLogger.info("Chain height: " + height); - } - } - else{ - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Request Failed"); - QuorumPingReceiverLogger.info("Request Failed"); - } - output.println(height); - - APIResponse.put("status", "Success"); - APIResponse.put("message", "Pong Sent"); - QuorumPingReceiverLogger.info("Pong Sent"); - - } - else { - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Pong Failed"); - QuorumPingReceiverLogger.info("Pong Failed"); - } - executeIPFSCommands(" ipfs p2p close -t /p2p/" + pingRequest); - output.close(); - input.close(); - sk.close(); - ss.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - return APIResponse.toString(); - } -} From 8d0fc28ee5af3791ab41ef12736a34ff14c1b4f0 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 28 Apr 2022 15:46:56 +0530 Subject: [PATCH 145/179] hashchain print stm Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 538ad96c..a5c2b2f5 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -15,14 +15,18 @@ public static String newHashChain(String miningTID, String[] DIDs) { finalHash = miningTID; - do { + if (finalHash != null) { - iterCount++; - finalHash = Functions.calculateHash(finalHash, "SHA3-256"); + do { - } while (ruleNotMatch(DIDs)); + iterCount++; + finalHash = Functions.calculateHash(finalHash, "SHA3-256"); + System.out.println("HashChain at " + iterCount + " is " + finalHash); - HashChainLogger.trace("Hash Chain Length for TID: " + miningTID + " is = " + iterCount); + } while (ruleNotMatch(DIDs)); + + HashChainLogger.debug("Hash Chain Length for TID: " + miningTID + " is = " + iterCount); + } return finalHash; } @@ -34,7 +38,7 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ } private static Boolean ruleNotMatch(String[] DIDs) { - HashChainLogger.trace("Hash Chain " + iterCount + " > " + finalHash); + // HashChainLogger.debug("Hash Chain " + iterCount + " > " + finalHash); int MATCH_RULE = 1; for (int i = 0; i < DIDs.length; i++) { From c6c4d6941e3f095a63dd1e734de7308bad7c444a Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Thu, 28 Apr 2022 18:07:45 +0530 Subject: [PATCH 146/179] length fix Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index a5c2b2f5..180bf0f5 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -15,7 +15,8 @@ public static String newHashChain(String miningTID, String[] DIDs) { finalHash = miningTID; - if (finalHash != null) { + if (finalHash != null && DIDs.length > 0) { + System.out.println(miningTID + " " + DIDs); do { @@ -39,7 +40,8 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ private static Boolean ruleNotMatch(String[] DIDs) { // HashChainLogger.debug("Hash Chain " + iterCount + " > " + finalHash); - int MATCH_RULE = 1; + int MATCH_RULE = DIDs.length; + System.out.println("MATCH_RULE = " + MATCH_RULE); for (int i = 0; i < DIDs.length; i++) { if (finalHash.substring(finalHash.length() - MATCH_RULE) From b5e5439af852cae14656fa295cb9dfec88a64fd5 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 29 Apr 2022 12:07:57 +0530 Subject: [PATCH 147/179] rm pom --- pom.xml | 43 ------------------------------------------- 1 file changed, 43 deletions(-) delete mode 100644 pom.xml diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 3ba08dd7..00000000 --- a/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - 4.0.0 - com.rubix.core - Kappa - 5000 - - src - - - src - - **/*.java - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 11 - 11 - - - - - - - com.did.core - did - provided - - - - - - com.did.core - did - 8.6 - - - - \ No newline at end of file From 20f3002ab94f11e68e406beefbc518827c1224b5 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Fri, 29 Apr 2022 12:09:00 +0530 Subject: [PATCH 148/179] rm yml --- java-rubix-core.iml | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 java-rubix-core.iml diff --git a/java-rubix-core.iml b/java-rubix-core.iml deleted file mode 100644 index 1c205d42..00000000 --- a/java-rubix-core.iml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file From 412e48b86c7bba7c365290ca43aa6fd0a7c47e50 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 2 May 2022 11:02:55 +0530 Subject: [PATCH 149/179] fix parts transfer check in staking check loop Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 14 ++++++-------- src/com/rubix/TokenTransfer/TokenReceiver.java | 5 ++--- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 180bf0f5..97ebce8d 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -16,15 +16,14 @@ public static String newHashChain(String miningTID, String[] DIDs) { finalHash = miningTID; if (finalHash != null && DIDs.length > 0) { - System.out.println(miningTID + " " + DIDs); - do { + while (ruleNotMatch(DIDs)) { iterCount++; finalHash = Functions.calculateHash(finalHash, "SHA3-256"); System.out.println("HashChain at " + iterCount + " is " + finalHash); - } while (ruleNotMatch(DIDs)); + } HashChainLogger.debug("Hash Chain Length for TID: " + miningTID + " is = " + iterCount); } @@ -40,12 +39,11 @@ public static Boolean verifyHashChain(String tokenTID, String finalHash, String[ private static Boolean ruleNotMatch(String[] DIDs) { // HashChainLogger.debug("Hash Chain " + iterCount + " > " + finalHash); - int MATCH_RULE = DIDs.length; - System.out.println("MATCH_RULE = " + MATCH_RULE); + int matchRule = DIDs.length; - for (int i = 0; i < DIDs.length; i++) { - if (finalHash.substring(finalHash.length() - MATCH_RULE) - .equals(DIDs[i].substring(DIDs[i].length() - MATCH_RULE))) { + for (int i = 0; i < matchRule; i++) { + if (finalHash.substring(finalHash.length() - matchRule) + .equals(DIDs[i].substring(DIDs[i].length() - matchRule))) { return false; } } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index cb794615..7f03e854 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -60,7 +60,6 @@ import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; -import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONArray; import org.json.JSONException; @@ -406,10 +405,10 @@ public static String receive() { JSONArray invalidTokens = new JSONArray(); - for (int count = 0; count < allTokensChains.length(); count++) { + for (int count = 0; count < wholeTokens.length(); count++) { String tokens = null; - JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); + JSONArray tokenChain = new JSONArray(wholeTokens.get(count).toString()); String TokenContent = get(wholeTokens.getString(count), ipfs); String tokenLevel = TokenContent.substring(0, TokenContent.length() - 64); String tokenNumberHash = TokenContent.substring(TokenContent.length() - 64); From 5f712e355e87780a7c62b0d6d08ec8073241da35 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 2 May 2022 11:11:32 +0530 Subject: [PATCH 150/179] fix missing import Signed-off-by: Nidhin Mahesh A --- src/com/rubix/TokenTransfer/TokenReceiver.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 7f03e854..4a86b39b 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -60,6 +60,7 @@ import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; +import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONArray; import org.json.JSONException; From 2cc9ff2ce6aef1fd9907d2efc7f1a03fe2acf23c Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 9 May 2022 12:01:56 +0530 Subject: [PATCH 151/179] hashchain iter Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 10 +- .../rubix/TokenTransfer/TokenReceiver.java | 127 +++++++++--------- 2 files changed, 67 insertions(+), 70 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 97ebce8d..724ecba1 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -30,23 +30,25 @@ public static String newHashChain(String miningTID, String[] DIDs) { return finalHash; } - public static Boolean verifyHashChain(String tokenTID, String finalHash, String[] DIDs) { + public static Boolean verifyHashChain(String tokenTID, String challengeHash, String[] DIDs) { String calculatedFinalHash = newHashChain(tokenTID, DIDs); - return calculatedFinalHash == finalHash; + return calculatedFinalHash == challengeHash; } private static Boolean ruleNotMatch(String[] DIDs) { - // HashChainLogger.debug("Hash Chain " + iterCount + " > " + finalHash); - int matchRule = DIDs.length; + int matchRule = 5; for (int i = 0; i < matchRule; i++) { if (finalHash.substring(finalHash.length() - matchRule) .equals(DIDs[i].substring(DIDs[i].length() - matchRule))) { + System.out.println("Rule " + i + " matched"); return false; } } + + System.out.println("Rule not matched"); return true; } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 4a86b39b..d4c270e0 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -216,63 +216,64 @@ public static String receive() { JSONObject amountLedger = tokenObject.getJSONObject("amountLedger"); TokenReceiverLogger.debug("Amount Ledger: " + amountLedger); int intPart = wholeTokens.length(); - // Double decimalPart = formatAmount(amount - intPart); - // JSONArray doubleSpentToken = new JSONArray(); - // boolean tokenOwners = true; - // ArrayList ownersArray = new ArrayList(); - // ArrayList previousSender = new ArrayList(); - // JSONArray ownersReceived = new JSONArray(); - // for (int i = 0; i < wholeTokens.length(); ++i) { - // try { - // TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + - // " Please wait..."); - // ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); - // - // if (ownersArray.size() > 2) { - // - // for (int j = 0; j < previousSendersArray.length(); j++) { - // if - // (previousSendersArray.getJSONObject(j).getString("token").equals(wholeTokens.getString(i))) - // ownersReceived = - // previousSendersArray.getJSONObject(j).getJSONArray("sender"); - // } - // - // for (int j = 0; j < ownersReceived.length(); j++) { - // previousSender.add(ownersReceived.getString(j)); - // } - // TokenReceiverLogger.debug("Previous Owners: " + previousSender); - // - // for (int j = 0; j < ownersArray.size(); j++) { - // if (!previousSender.contains(ownersArray.get(j).toString())) - // tokenOwners = false; - // } - // } - // } catch (IOException e) { - // - // TokenReceiverLogger.debug("Ipfs dht find did not execute"); - // } - // } - // if (!tokenOwners) { - // JSONArray owners = new JSONArray(); - // for (int i = 0; i < ownersArray.size(); i++) - // owners.put(ownersArray.get(i).toString()); - // TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); - // TokenReceiverLogger.debug("Owners: " + owners); - // output.println("420"); - // output.println(doubleSpentToken.toString()); - // output.println(owners.toString()); - // APIResponse.put("did", senderDidIpfsHash); - // APIResponse.put("tid", "null"); - // APIResponse.put("status", "Failed"); - // APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + - // owners); - // IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - // output.close(); - // input.close(); - // sk.close(); - // ss.close(); - // return APIResponse.toString(); - // } + // ? multiple pin check starts + Double decimalPart = formatAmount(amount - intPart); + JSONArray doubleSpentToken = new JSONArray(); + boolean tokenOwners = true; + ArrayList ownersArray = new ArrayList(); + ArrayList previousSender = new ArrayList(); + JSONArray ownersReceived = new JSONArray(); + for (int i = 0; i < wholeTokens.length(); ++i) { + try { + TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + + " Please wait..."); + ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); + + if (ownersArray.size() > 2) { + + for (int j = 0; j < previousSendersArray.length(); j++) { + if (previousSendersArray.getJSONObject(j).getString("token") + .equals(wholeTokens.getString(i))) + ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); + } + + for (int j = 0; j < ownersReceived.length(); j++) { + previousSender.add(ownersReceived.getString(j)); + } + TokenReceiverLogger.debug("Previous Owners: " + previousSender); + + for (int j = 0; j < ownersArray.size(); j++) { + if (!previousSender.contains(ownersArray.get(j).toString())) + tokenOwners = false; + } + } + } catch (IOException e) { + + TokenReceiverLogger.debug("Ipfs dht find did not execute"); + } + } + if (!tokenOwners) { + JSONArray owners = new JSONArray(); + for (int i = 0; i < ownersArray.size(); i++) + owners.put(ownersArray.get(i).toString()); + TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); + TokenReceiverLogger.debug("Owners: " + owners); + output.println("420"); + output.println(doubleSpentToken.toString()); + output.println(owners.toString()); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + + owners); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + // ? multiple pin check ends String senderToken = TokenDetails.toString(); String consensusID = calculateHash(senderToken, "SHA3-256"); writeToFile(LOGGER_PATH + "consensusID", consensusID, false); @@ -471,6 +472,9 @@ public static String receive() { return APIResponse.toString(); } + // ! check quorum signs for previous transaction for the tokenchain to verify + // ! the ownership of sender for the token + if ((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); @@ -499,15 +503,8 @@ public static String receive() { invalidTokens.put(tokens); } - // ! staking checks (1..4) starts here - - // ! staking checks (1): Check incoming token level - if (ownerCheck && (tokenChain.length() < minumumStakeHeight)) { // && (tokenNumber > 1204400) - - // ! staking checks (3): Verify the signatures earned during the mining of the - // ! incoming mint token JSONObject genesiObject = tokenChain.getJSONObject(0); JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); @@ -552,8 +549,6 @@ public static String receive() { // invalidTokens.put(tokens); // } - // ! staking checks (2): For incoming new mint token, verify the staked token - if (stakeDataArray.length() == 3) { JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); From d47f076dc36f04ce0928a6a4c2b5235380f5841b Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 10 May 2022 11:25:46 +0530 Subject: [PATCH 152/179] reverse hashchain Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 84 ++++++++++++------- .../rubix/TokenTransfer/TokenReceiver.java | 14 ++-- 2 files changed, 61 insertions(+), 37 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 724ecba1..b4c40775 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -8,48 +8,72 @@ public class HashChain { public static Logger HashChainLogger = Logger.getLogger(HashChain.class); - private static String finalHash = ""; - private static int iterCount = 0; + // write a function which takes a string as TID and string array as DIDs. DIDs + // will hash itself continuously and return when the last 3 char of hash matches + // last 3 char of TID + private static String getHashChain(String tID, String[] DIDs) { + String hashChain = ""; + int counter = 0; + for (String DID : DIDs) { + + String hash = DID; + while (!hash.endsWith(tID.substring(tID.length() - DIDs.length))) { + // hashChain += hash; + counter++; + hash = Functions.calculateHash(hash, "SHA3-256"); + hashChain = hash; + System.out.println(hash + " " + counter); + } - public static String newHashChain(String miningTID, String[] DIDs) { + } - finalHash = miningTID; + return hashChain; - if (finalHash != null && DIDs.length > 0) { + } + // private static String finalHash = ""; + // private static int iterCount = 0; - while (ruleNotMatch(DIDs)) { + // public static String newHashChain(String miningTID, String[] DIDs) { - iterCount++; - finalHash = Functions.calculateHash(finalHash, "SHA3-256"); - System.out.println("HashChain at " + iterCount + " is " + finalHash); + // finalHash = miningTID; - } + // if (finalHash != null && DIDs.length > 0) { - HashChainLogger.debug("Hash Chain Length for TID: " + miningTID + " is = " + iterCount); - } - return finalHash; - } + // while (ruleNotMatch(DIDs)) { - public static Boolean verifyHashChain(String tokenTID, String challengeHash, String[] DIDs) { + // iterCount++; + // finalHash = Functions.calculateHash(finalHash, "SHA3-256"); + // System.out.println("HashChain at " + iterCount + " is " + finalHash); - String calculatedFinalHash = newHashChain(tokenTID, DIDs); + // } - return calculatedFinalHash == challengeHash; - } + // HashChainLogger.debug("Hash Chain Length for TID: " + miningTID + " is = " + + // iterCount); + // } + // return finalHash; + // } - private static Boolean ruleNotMatch(String[] DIDs) { - int matchRule = 5; + // public static Boolean verifyHashChain(String tokenTID, String challengeHash, + // String[] DIDs) { - for (int i = 0; i < matchRule; i++) { - if (finalHash.substring(finalHash.length() - matchRule) - .equals(DIDs[i].substring(DIDs[i].length() - matchRule))) { - System.out.println("Rule " + i + " matched"); - return false; - } - } + // String calculatedFinalHash = newHashChain(tokenTID, DIDs); - System.out.println("Rule not matched"); - return true; - } + // return calculatedFinalHash == challengeHash; + // } + + // private static Boolean ruleNotMatch(String[] DIDs) { + // int matchRule = 5; + + // for (int i = 0; i < 3; i++) { + // if (finalHash.substring(finalHash.length() - matchRule) + // .equals(DIDs[i].substring(DIDs[i].length() - matchRule))) { + // System.out.println("Rule " + i + " matched"); + // return false; + // } + // } + + // System.out.println("Rule not matched"); + // return true; + // } } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index d4c270e0..030e5182 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -220,16 +220,16 @@ public static String receive() { Double decimalPart = formatAmount(amount - intPart); JSONArray doubleSpentToken = new JSONArray(); boolean tokenOwners = true; - ArrayList ownersArray = new ArrayList(); + ArrayList pinOwnersArray = new ArrayList(); ArrayList previousSender = new ArrayList(); JSONArray ownersReceived = new JSONArray(); for (int i = 0; i < wholeTokens.length(); ++i) { try { TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + " Please wait..."); - ownersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); + pinOwnersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); - if (ownersArray.size() > 2) { + if (pinOwnersArray.size() > 2) { for (int j = 0; j < previousSendersArray.length(); j++) { if (previousSendersArray.getJSONObject(j).getString("token") @@ -242,8 +242,8 @@ public static String receive() { } TokenReceiverLogger.debug("Previous Owners: " + previousSender); - for (int j = 0; j < ownersArray.size(); j++) { - if (!previousSender.contains(ownersArray.get(j).toString())) + for (int j = 0; j < pinOwnersArray.size(); j++) { + if (!previousSender.contains(pinOwnersArray.get(j).toString())) tokenOwners = false; } } @@ -254,8 +254,8 @@ public static String receive() { } if (!tokenOwners) { JSONArray owners = new JSONArray(); - for (int i = 0; i < ownersArray.size(); i++) - owners.put(ownersArray.get(i).toString()); + for (int i = 0; i < pinOwnersArray.size(); i++) + owners.put(pinOwnersArray.get(i).toString()); TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); TokenReceiverLogger.debug("Owners: " + owners); output.println("420"); From 1cfb07615cb8f087e5e3f4f9195254690f697261 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 10 May 2022 11:26:26 +0530 Subject: [PATCH 153/179] fix func name Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index b4c40775..5cdb32cd 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -11,7 +11,7 @@ public class HashChain { // write a function which takes a string as TID and string array as DIDs. DIDs // will hash itself continuously and return when the last 3 char of hash matches // last 3 char of TID - private static String getHashChain(String tID, String[] DIDs) { + private static String newHashChain(String tID, String[] DIDs) { String hashChain = ""; int counter = 0; for (String DID : DIDs) { From e366a6a497cc1e65c5eabbac697b2cafb0ba15c0 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 10 May 2022 11:38:21 +0530 Subject: [PATCH 154/179] fix method access Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 5cdb32cd..bbf111c0 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -11,7 +11,7 @@ public class HashChain { // write a function which takes a string as TID and string array as DIDs. DIDs // will hash itself continuously and return when the last 3 char of hash matches // last 3 char of TID - private static String newHashChain(String tID, String[] DIDs) { + public static String newHashChain(String tID, String[] DIDs) { String hashChain = ""; int counter = 0; for (String DID : DIDs) { From 8d78bf0c29110090889f015a0021ad6d0079f054 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 10 May 2022 12:16:04 +0530 Subject: [PATCH 155/179] averaging puzzle Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 104 ++++++++++++++-------------- 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index bbf111c0..ffed61b3 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -8,72 +8,72 @@ public class HashChain { public static Logger HashChainLogger = Logger.getLogger(HashChain.class); - // write a function which takes a string as TID and string array as DIDs. DIDs - // will hash itself continuously and return when the last 3 char of hash matches - // last 3 char of TID - public static String newHashChain(String tID, String[] DIDs) { - String hashChain = ""; - int counter = 0; - for (String DID : DIDs) { - - String hash = DID; - while (!hash.endsWith(tID.substring(tID.length() - DIDs.length))) { - // hashChain += hash; - counter++; - hash = Functions.calculateHash(hash, "SHA3-256"); - hashChain = hash; - System.out.println(hash + " " + counter); - } - + // write a function which takes a string as TID and string array as DIDs. The + // function should return the average iterations each DID took to rehash itself + // to match the last 3 char of TID + public static String newHashChain(String TID, String[] DIDs) { + int[] averageIterations = new int[DIDs.length]; + for (int i = 0; i < DIDs.length; i++) { + averageIterations[i] = averageIterations(TID, DIDs[i]); } - - return hashChain; - + // get the average of values in the array + int sum = 0; + for (int i = 0; i < averageIterations.length; i++) { + System.out.println("averageIterations[" + i + "] = " + averageIterations[i]); + sum += averageIterations[i]; + } + int average = sum / averageIterations.length; + return Integer.toString(average); } - // private static String finalHash = ""; - // private static int iterCount = 0; - - // public static String newHashChain(String miningTID, String[] DIDs) { - // finalHash = miningTID; + private static int averageIterations(String TID, String DID) { + int iterations = 0; + int matchRule = 5; + String last3Chars = TID.substring(TID.length() - matchRule); + String currentDID = DID; + while (!currentDID.substring(currentDID.length() - matchRule).equals(last3Chars)) { + currentDID = Functions.calculateHash(currentDID, "SHA3-256"); + iterations++; - // if (finalHash != null && DIDs.length > 0) { - - // while (ruleNotMatch(DIDs)) { + System.out.println(currentDID + " " + iterations); + } + return iterations; + } - // iterCount++; - // finalHash = Functions.calculateHash(finalHash, "SHA3-256"); - // System.out.println("HashChain at " + iterCount + " is " + finalHash); + // write a function which takes a string as TID and string array as DIDs. TID + // will hash itself until last 5 characters are same as any one of the DIDs. + // If not found, return null. + // public static String newHashChain(String TID, String[] DIDs) { + // String TIDHash = TID; + // while (!Functions.isSame(TIDHash.substring(TIDHash.length() - 5), DIDs)) { + // TIDHash = Functions.calculateHash(TIDHash, "SHA3-256"); // } - // HashChainLogger.debug("Hash Chain Length for TID: " + miningTID + " is = " + - // iterCount); - // } - // return finalHash; + // return TIDHash; // } - // public static Boolean verifyHashChain(String tokenTID, String challengeHash, - // String[] DIDs) { - - // String calculatedFinalHash = newHashChain(tokenTID, DIDs); - - // return calculatedFinalHash == challengeHash; + // write a function which takes a string as TID and string array as DIDs. DIDs + // will hash itself continuously and return when the last 3 char of hash matches + // last 3 char of TID + // public static String newHashChain(String tID, String[] DIDs) { + // String hashChain = ""; + // int counter = 0; + // for (String DID : DIDs) { + + // String hash = DID; + // while (!hash.endsWith(tID.substring(tID.length() - DIDs.length))) { + // // hashChain += hash; + // counter++; + // hash = Functions.calculateHash(hash, "SHA3-256"); + // hashChain = hash; + // System.out.println(hash + " " + counter); // } - // private static Boolean ruleNotMatch(String[] DIDs) { - // int matchRule = 5; - - // for (int i = 0; i < 3; i++) { - // if (finalHash.substring(finalHash.length() - matchRule) - // .equals(DIDs[i].substring(DIDs[i].length() - matchRule))) { - // System.out.println("Rule " + i + " matched"); - // return false; - // } // } - // System.out.println("Rule not matched"); - // return true; + // return hashChain; + // } } From 78f42a0f13501788c43ad144021786c6c00e3344 Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 10 May 2022 12:38:37 +0530 Subject: [PATCH 156/179] dynamic match rule Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index ffed61b3..827b10b3 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -11,10 +11,10 @@ public class HashChain { // write a function which takes a string as TID and string array as DIDs. The // function should return the average iterations each DID took to rehash itself // to match the last 3 char of TID - public static String newHashChain(String TID, String[] DIDs) { + public static String newHashChain(String TID, String[] DIDs, int matchRule) { int[] averageIterations = new int[DIDs.length]; for (int i = 0; i < DIDs.length; i++) { - averageIterations[i] = averageIterations(TID, DIDs[i]); + averageIterations[i] = averageIterations(TID, DIDs[i], matchRule); } // get the average of values in the array int sum = 0; @@ -26,17 +26,17 @@ public static String newHashChain(String TID, String[] DIDs) { return Integer.toString(average); } - private static int averageIterations(String TID, String DID) { + private static int averageIterations(String TID, String DID, matchRule) { int iterations = 0; - int matchRule = 5; String last3Chars = TID.substring(TID.length() - matchRule); String currentDID = DID; while (!currentDID.substring(currentDID.length() - matchRule).equals(last3Chars)) { currentDID = Functions.calculateHash(currentDID, "SHA3-256"); iterations++; - System.out.println(currentDID + " " + iterations); } + System.out.println(currentDID + " " + iterations); + return iterations; } From 771541fbb45db369e60097858525986d55ae7aff Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Tue, 10 May 2022 18:06:33 +0530 Subject: [PATCH 157/179] hashchain cleanup Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Mining/HashChain.java | 96 ++++++++++++++++++++--------- 1 file changed, 66 insertions(+), 30 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 827b10b3..505ef633 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -8,41 +8,80 @@ public class HashChain { public static Logger HashChainLogger = Logger.getLogger(HashChain.class); - // write a function which takes a string as TID and string array as DIDs. The - // function should return the average iterations each DID took to rehash itself - // to match the last 3 char of TID - public static String newHashChain(String TID, String[] DIDs, int matchRule) { - int[] averageIterations = new int[DIDs.length]; - for (int i = 0; i < DIDs.length; i++) { - averageIterations[i] = averageIterations(TID, DIDs[i], matchRule); - } - // get the average of values in the array - int sum = 0; - for (int i = 0; i < averageIterations.length; i++) { - System.out.println("averageIterations[" + i + "] = " + averageIterations[i]); - sum += averageIterations[i]; + public static String newHashChain(String tID, String[] DIDs, int rule) { + String hashChain = ""; + + for (String DID : DIDs) { + + int counter = 0; + String hash = DID; + while (!hash.endsWith(tID.substring(tID.length() - rule))) { + counter++; + hash = Functions.calculateHash(hash, "SHA3-256"); + hashChain = hash; + + } + System.out.println(hash + " " + counter); } - int average = sum / averageIterations.length; - return Integer.toString(average); + return hashChain; } - private static int averageIterations(String TID, String DID, matchRule) { - int iterations = 0; - String last3Chars = TID.substring(TID.length() - matchRule); - String currentDID = DID; - while (!currentDID.substring(currentDID.length() - matchRule).equals(last3Chars)) { - currentDID = Functions.calculateHash(currentDID, "SHA3-256"); - iterations++; + // using the TID and DIDs, - } - System.out.println(currentDID + " " + iterations); + // fetch TID and DIDs as inputs. TID will hash itself until the last 3 char of + // TID matches with any of the DIDs in the list. - return iterations; - } + // public static String getTID(String TID, String DIDs) { + + // token is the TID that + + // public static String newHashChain(String TID, String[] DIDs) { + // String TIDHash = TID; + + // while (!(TIDHash.substring(TIDHash.length() - 5), DIDs)) { + // TIDHash = Functions.calculateHash(TIDHash, "SHA3-256"); + // } + + // return TIDHash; + // } // write a function which takes a string as TID and string array as DIDs. TID // will hash itself until last 5 characters are same as any one of the DIDs. // If not found, return null. + + // write a function which takes a string as TID and string array as DIDs. The + // function should return the average iterations each DID took to rehash itself + // to match the last 3 char of TID + // public static String newHashChain(String TID, String[] DIDs, int matchRule) { + // int[] averageIterations = new int[DIDs.length]; + // for (int i = 0; i < DIDs.length; i++) { + // averageIterations[i] = averageIterations(TID, DIDs[i], matchRule); + // } + // // get the average of values in the array + // int sum = 0; + // for (int i = 0; i < averageIterations.length; i++) { + // System.out.println("averageIterations[" + i + "] = " + averageIterations[i]); + // sum += averageIterations[i]; + // } + // int average = sum / averageIterations.length; + // return Integer.toString(average); + // } + + // private static int averageIterations(String TID, String DID, int matchRule) { + // int iterations = 0; + // String last3Chars = TID.substring(TID.length() - matchRule); + // String currentDID = DID; + // while (!currentDID.substring(currentDID.length() - + // matchRule).equals(last3Chars)) { + // currentDID = Functions.calculateHash(currentDID, "SHA3-256"); + // iterations++; + + // } + // System.out.println(currentDID + " " + iterations); + + // return iterations; + // } + // public static String newHashChain(String TID, String[] DIDs) { // String TIDHash = TID; @@ -53,10 +92,7 @@ private static int averageIterations(String TID, String DID, matchRule) { // return TIDHash; // } - // write a function which takes a string as TID and string array as DIDs. DIDs - // will hash itself continuously and return when the last 3 char of hash matches - // last 3 char of TID - // public static String newHashChain(String tID, String[] DIDs) { + // public static String newHashChain(String tID, String[] DIDs, int matchRule) { // String hashChain = ""; // int counter = 0; // for (String DID : DIDs) { From b362c02ead741f415eded2cb9a5b96e8f115bcac Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Thu, 12 May 2022 12:00:44 +0530 Subject: [PATCH 158/179] Updated HashChain Consistency Updated HashChain to take min duration of an hour --- src/com/rubix/Mining/HashChain.java | 38 +++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 505ef633..7f320f1e 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -5,25 +5,49 @@ import org.apache.log4j.Logger; public class HashChain { + static String hashChain = ""; public static Logger HashChainLogger = Logger.getLogger(HashChain.class); public static String newHashChain(String tID, String[] DIDs, int rule) { - String hashChain = ""; - - for (String DID : DIDs) { - + long totalTime = 0; + long currentTime = 0; + int ctr = 0; + java.util.Date date = new java.util.Date(); + while(totalTime<3600000 || rule > tID.length()) { + + currentTime = hashChainCounter(tID, DIDs,rule+ctr); + totalTime = totalTime + currentTime; + //System.out.println("Counter is "+ctr+" Current time used is "+ totalTime); + ctr++; + currentTime = 0; + + + } + return hashChain; + + } + + + public static long hashChainCounter(String tID, String[] DIDs, int rule) { + //String hashChain = ""; + long start = 0; + long end = 0; + start = System.currentTimeMillis(); + for (String DID : DIDs) { int counter = 0; String hash = DID; while (!hash.endsWith(tID.substring(tID.length() - rule))) { counter++; hash = Functions.calculateHash(hash, "SHA3-256"); hashChain = hash; - } - System.out.println(hash + " " + counter); + + // System.out.println(hash + " " + counter + " rule is "+ rule); } - return hashChain; + end = System.currentTimeMillis(); + // System.out.println("Current time "+(end - start)); + return (end - start); } // using the TID and DIDs, From 34cef7f8049cfe8ba208a8875e172ec08cbaa69e Mon Sep 17 00:00:00 2001 From: Nidhin Mahesh A Date: Mon, 23 May 2022 19:39:35 +0530 Subject: [PATCH 159/179] moving updateQuorum to bottom Signed-off-by: Nidhin Mahesh A --- src/com/rubix/Resources/Functions.java | 64 +++++++++----------- src/com/rubix/TokenTransfer/TokenSender.java | 41 +++++++------ 2 files changed, 51 insertions(+), 54 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 6784f853..3340e640 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -9,12 +9,6 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import static com.rubix.Resources.IPFSNetwork.swarmConnectProcess; -import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Ping.PingCheck; - -import io.ipfs.api.IPFS; -import io.ipfs.multiaddr.MultiAddress; - import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.DataOutputStream; @@ -44,18 +38,17 @@ import javax.imageio.ImageIO; +import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Ping.PingCheck; + import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; -import org.json.*; - - - - - - +import io.ipfs.api.IPFS; +import io.ipfs.multiaddr.MultiAddress; public class Functions { @@ -997,6 +990,7 @@ public static void updateQuorum(JSONArray quorumArray, JSONArray signedQuorumLis dataToSendQuorumUpdate.put("signedquorum", signedQuorumList); dataToSendQuorumUpdate.put("status", status); String populateQuorumUpdate = dataToSendQuorumUpdate.toString(); + FunctionsLogger.debug("Sending 'POST' request to URL : " + urlQuorumUpdate); conQuorumUpdate.setDoOutput(true); DataOutputStream wrQuorumUpdate = new DataOutputStream(conQuorumUpdate.getOutputStream()); @@ -1005,7 +999,6 @@ public static void updateQuorum(JSONArray quorumArray, JSONArray signedQuorumLis wrQuorumUpdate.close(); int responseCodeQuorumUpdate = conQuorumUpdate.getResponseCode(); - FunctionsLogger.debug("Sending 'POST' request to URL : " + urlQuorumUpdate); FunctionsLogger.debug("Post Data : " + populateQuorumUpdate); FunctionsLogger.debug("Response Code : " + responseCodeQuorumUpdate); @@ -1438,7 +1431,7 @@ public static Double getBalance() throws JSONException { return balance; } - public static String initHash(){ + public static String initHash() { String version = ""; try { URL url = new URL("http://localhost:1898/getVersion"); @@ -1456,7 +1449,7 @@ public static String initHash(){ version = output; } conn.disconnect(); - FunctionsLogger.debug("initHash version is "+version); + FunctionsLogger.debug("initHash version is " + version); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { @@ -1464,19 +1457,21 @@ public static String initHash(){ } return version; } - - - - /*public static String initHash() throws IOException { - String initPath = Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - initPath = initPath.split("\\.jar")[0]; - initPath = initPath.split("file:", 2)[1]; - String jarName[] = initPath.split("\\/"); - initPath = jarName[jarName.length-1]; - initPath = initPath + ".jar"; - String hash = calculateFileHash(initPath, "SHA3-256"); - return hash; - }*/ + + /* + * public static String initHash() throws IOException { + * String initPath = + * Functions.class.getProtectionDomain().getCodeSource().getLocation().getPath() + * ; + * initPath = initPath.split("\\.jar")[0]; + * initPath = initPath.split("file:", 2)[1]; + * String jarName[] = initPath.split("\\/"); + * initPath = jarName[jarName.length-1]; + * initPath = initPath + ".jar"; + * String hash = calculateFileHash(initPath, "SHA3-256"); + * return hash; + * } + */ public static Double partTokenBalance(String tokenHash) throws JSONException { pathSet(); @@ -1559,8 +1554,9 @@ public static void backgroundChecks() { public static String sanityMessage; - public static boolean sanityCheck(String userType, String peerid, IPFS ipfs, int port) throws IOException, JSONException { - FunctionsLogger.info("Entering " + userType +" SanityCheck"); + public static boolean sanityCheck(String userType, String peerid, IPFS ipfs, int port) + throws IOException, JSONException { + FunctionsLogger.info("Entering " + userType + " SanityCheck"); boolean sanityCheckErrorFlag = true; if (sanityCheckErrorFlag && checkIPFSStatus(peerid, ipfs)) { FunctionsLogger.debug(userType + " IPFS is working in " + peerid); @@ -1574,13 +1570,13 @@ public static boolean sanityCheck(String userType, String peerid, IPFS ipfs, int if (sanityCheckErrorFlag) { if (bootstrapConnect(peerid, ipfs)) { - FunctionsLogger.debug("Bootstrap connected for "+userType +" : " + peerid); + FunctionsLogger.debug("Bootstrap connected for " + userType + " : " + peerid); FunctionsLogger.debug("Bootstrap check true"); } else { sanityCheckErrorFlag = false; - FunctionsLogger.debug("Bootstrap connection unsuccessful for "+userType + " : " + peerid); + FunctionsLogger.debug("Bootstrap connection unsuccessful for " + userType + " : " + peerid); FunctionsLogger.debug("Bootstrap check false"); - sanityMessage = "Bootstrap connection unsuccessful for "+userType +" : " + peerid; + sanityMessage = "Bootstrap connection unsuccessful for " + userType + " : " + peerid; } } diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index bfb4b194..092ca843 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -38,16 +38,11 @@ import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; import static com.rubix.Resources.IPFSNetwork.unpin; -import com.rubix.AuthenticateNode.PropImage; -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 java.awt.image.BufferedImage; 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; @@ -55,19 +50,27 @@ 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.imageio.ImageIO; import javax.net.ssl.HttpsURLConnection; + +import com.rubix.AuthenticateNode.PropImage; +import com.rubix.Consensus.InitiatorConsensus; +import com.rubix.Consensus.InitiatorProcedure; +import com.rubix.Resources.Functions; +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 TokenSender { private static final Logger TokenSenderLogger = Logger.getLogger(TokenSender.class); @@ -111,7 +114,7 @@ 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); - boolean sanityCheck = sanityCheck("Receiver",receiverPeerId, ipfs, port + 10); + boolean sanityCheck = sanityCheck("Receiver", receiverPeerId, ipfs, port + 10); if (!sanityCheck) { APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); @@ -428,7 +431,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception for (int i = 0; i < quorumArray.length(); i++) { String quorumPeerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", quorumArray.getString(i)); - boolean quorumSanityCheck = sanityCheck("Quorum",quorumPeerID, ipfs, port + 11); + boolean quorumSanityCheck = sanityCheck("Quorum", quorumPeerID, ipfs, port + 11); if (!quorumSanityCheck) { sanityFailedQuorum.put(quorumPeerID); @@ -879,8 +882,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("receiver", receiverDidIpfsHash); APIResponse.put("totaltime", totalTime); - updateQuorum(quorumArray, signedQuorumList, true, type); - JSONObject transactionRecord = new JSONObject(); transactionRecord.put("role", "Sender"); transactionRecord.put("tokens", allTokens); @@ -1030,6 +1031,13 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } + TokenSenderLogger.info("Transaction Successful"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + updateQuorum(quorumArray, signedQuorumList, true, type); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; // Populating data to explorer if (!EXPLORER_IP.contains("127.0.0.1")) { @@ -1085,13 +1093,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception TokenSenderLogger.debug(response.toString()); } - - TokenSenderLogger.info("Transaction Successful"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - output.close(); - input.close(); - senderSocket.close(); - senderMutex = false; return APIResponse; } From 28ea1104515deda58d384988666ef5a2f826a724 Mon Sep 17 00:00:00 2001 From: Allen Iype P Cherian Date: Wed, 25 May 2022 15:18:13 +0530 Subject: [PATCH 160/179] API for updating owner identity --- src/com/rubix/Resources/Functions.java | 57 ++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 3340e640..1a10d6fb 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -37,6 +37,7 @@ import java.util.Set; import javax.imageio.ImageIO; +import javax.json.JsonArray; import com.rubix.AuthenticateNode.PropImage; import com.rubix.Ping.PingCheck; @@ -1849,4 +1850,60 @@ public static boolean portStatusWindows(int port) { } + public static void ownerIdentity(JSONArray tokens, String receiverDidIpfsHash) { + Functions.pathSet(); + + try { + for (int i = 0; i < tokens.length(); i++) { + + String tokenHash = tokens.getString(i); + String hashString = tokenHash.concat(receiverDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + BufferedImage pvt = ImageIO.read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(pvt); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + String ownerIdentity = hashForPositions.concat(positions); + String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); + File chainFile = new File(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + if (chainFile.exists()) { + String tokenChainFile = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + JSONArray tokenChainArray = new JSONArray(tokenChainFile); + JSONObject tokenChainObject = tokenChainArray.getJSONObject(tokenChainArray.length() - 1); + tokenChainObject.put("owner", ownerIdentityHash); + tokenChainArray.remove(tokenChainArray.length() - 1); + tokenChainArray.put(tokenChainObject); + writeToFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json"), tokenChainArray.toString(), false); + + } else { + File partChainFile = new File(TOKENCHAIN_PATH.concat("PARTS/").concat(tokenHash).concat(".json")); + if (partChainFile.exists()) { + String tokenChainFile = readFile(TOKENCHAIN_PATH.concat("PARTS/").concat(tokenHash).concat(".json")); + JSONArray tokenChainArray = new JSONArray(tokenChainFile); + JSONObject tokenChainObject = tokenChainArray.getJSONObject(tokenChainArray.length() - 1); + tokenChainObject.put("owner", ownerIdentityHash); + tokenChainArray.remove(tokenChainArray.length() - 1); + tokenChainArray.put(tokenChainObject); + writeToFile(TOKENCHAIN_PATH.concat("PARTS/").concat(tokenHash).concat(".json"), tokenChainArray.toString(), false); + + } else { + FunctionsLogger.info("Token chain file not found for token " + tokenHash); + } + + } + + + } + } catch (Exception e) { + FunctionsLogger.error("Exception occured at ownerIdentity", e); + } + + + + } + } From 2dddf99ec84ce7a8a4cb6211b0f6f964e58309fd Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Mon, 30 May 2022 17:04:18 +0530 Subject: [PATCH 161/179] HashChain + Multiple pin check from sender side --- src/com/rubix/Consensus/StakeConsensus.java | 14 +- src/com/rubix/Mining/HashChain.java | 18 +- src/com/rubix/Mining/ProofCredits.java | 34 +- src/com/rubix/Resources/Functions.java | 75 + .../rubix/TokenTransfer/TokenReceiver.java | 2334 ++++++++--------- src/com/rubix/TokenTransfer/TokenSender.java | 120 +- 6 files changed, 1353 insertions(+), 1242 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 3ba3de33..ccc5084b 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -19,14 +19,14 @@ import java.net.SocketException; 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.JSONObject; +import com.rubix.AuthenticateNode.Authenticate; +import com.rubix.Resources.IPFSNetwork; + import io.ipfs.api.IPFS; public class StakeConsensus { @@ -36,6 +36,7 @@ public class StakeConsensus { public static volatile int STAKE_SUCCESS = 0; public static volatile int STAKE_FAILED = 0; public static volatile JSONArray stakeDetails = new JSONArray(); + public static volatile ArrayList stakedDIDs = new ArrayList(); // MINE_ID // QST_HEIGHT // STAKED_QUORUM_DID @@ -57,7 +58,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject String[] quorumPID = new String[signedAphaQuorumArray.length()]; StakeConsensusLogger.debug("Initiating Staking with " + signedAphaQuorumArray.length() + " Alpha Quorums: " - + signedAphaQuorumArray); + + signedAphaQuorumArray.toString()); try { @@ -97,7 +98,8 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject "peerid", quorumPID[j]); - StakeConsensusLogger.debug("Mined Token Details sent for validation...DID: " + stakerDID); + StakeConsensusLogger.debug("Mined Token Details sent for validation...Staker DID is : " + stakerDID); + try { qResponse[j] = qIn[j].readLine(); @@ -194,6 +196,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject // ! add mine signs to tokenchain StakeConsensusLogger.debug("Adding mine signatures"); JSONObject mineSigns = new JSONObject(qResponse[j]); + StakeConsensusLogger.debug("mineSign is "+mineSigns.toString()); if (mineSigns.length() > 0) { @@ -239,6 +242,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject // qOut[j].println("200"); StakeConsensusLogger.debug( "Staking completed for Peer: " + quorumPID[j]); + stakedDIDs.add(STAKED_QUORUM_DID); stakeDetails.put(mineSigns); STAKE_SUCCESS++; }else { diff --git a/src/com/rubix/Mining/HashChain.java b/src/com/rubix/Mining/HashChain.java index 7f320f1e..3039ef6b 100644 --- a/src/com/rubix/Mining/HashChain.java +++ b/src/com/rubix/Mining/HashChain.java @@ -2,6 +2,9 @@ import com.rubix.Resources.Functions; +import java.util.ArrayList; +import java.util.Random; + import org.apache.log4j.Logger; public class HashChain { @@ -14,9 +17,9 @@ public static String newHashChain(String tID, String[] DIDs, int rule) { long currentTime = 0; int ctr = 0; java.util.Date date = new java.util.Date(); - while(totalTime<3600000 || rule > tID.length()) { + while(totalTime<3600000 || rule > tID.length()) { - currentTime = hashChainCounter(tID, DIDs,rule+ctr); + // currentTime = hashChainCounter(tID, DIDs,rule+ctr); totalTime = totalTime + currentTime; //System.out.println("Counter is "+ctr+" Current time used is "+ totalTime); ctr++; @@ -29,12 +32,15 @@ public static String newHashChain(String tID, String[] DIDs, int rule) { } - public static long hashChainCounter(String tID, String[] DIDs, int rule) { + public static String hashChainCounter(String tID, ArrayList DIDs, int rule) { //String hashChain = ""; long start = 0; long end = 0; start = System.currentTimeMillis(); - for (String DID : DIDs) { + Random rand = new Random(); + String DID = DIDs.get(rand.nextInt(3)) ; + //DIDs[rand.nextInt(3)]; + //for (String DID : DIDs) { int counter = 0; String hash = DID; while (!hash.endsWith(tID.substring(tID.length() - rule))) { @@ -44,10 +50,10 @@ public static long hashChainCounter(String tID, String[] DIDs, int rule) { } // System.out.println(hash + " " + counter + " rule is "+ rule); - } + // } end = System.currentTimeMillis(); // System.out.println("Current time "+(end - start)); - return (end - start); + return hashChain; } // using the TID and DIDs, diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 9e45ae2b..0edf488c 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -67,6 +67,7 @@ public class ProofCredits { private static ArrayList betaPeersList; private static ArrayList gammaPeersList; private static int alphaSize = 0; + public static String hashChainProof = new String(); public static JSONObject create(String data, IPFS ipfs) throws IOException, JSONException { @@ -224,6 +225,26 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON // writeToFile(LOGGER_PATH + "tempgamma", tid.concat(DID), false); // String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); // deleteFile(LOGGER_PATH + "tempgamma"); + + + + ProofCreditsLogger.debug("DID is "+DID); + ProofCreditsLogger.debug("Quorums list is "+quorumArray.toString()); + if(quorumArray.toString().contains(DID)) { + JSONArray updatedQuourmList = new JSONArray(); + ProofCreditsLogger.debug("Miner DID "+ DID + "is found in quourmArray"); + for(int i=0;i 0) { tokenChainGenesisObject.put(MiningConstants.MINE_ID, StakeConsensus.stakeDetails); tokenChainArray.put(tokenChainGenesisObject); ProofCreditsLogger.debug("Stake Details for new mined token: " + StakeConsensus.stakeDetails); + ProofCreditsLogger.debug("Staked quorums are "+ StakeConsensus.stakedDIDs); + ProofCreditsLogger.debug("-----------------------------------------------"); + ProofCreditsLogger.debug("Staked quorums are :"); + for (String ele : StakeConsensus.stakedDIDs) { + ProofCreditsLogger.debug(ele+" "); + } + ProofCreditsLogger.debug("-----------------------------------------------"); writeToFile(TOKENS_PATH + tokenHash, token.getString(i), false); ProofCreditsLogger.warn(" TOKENHASH " + tokenHash); ProofCreditsLogger.warn(" TOKENS " + token.getString(i)); @@ -475,6 +503,8 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON temp.put("tokenHash", tokenHash); JSONArray tempArray = new JSONArray(); tempArray.put(temp); + hashChainProof = HashChain.hashChainCounter(tid, StakeConsensus.stakedDIDs, 6); + ProofCreditsLogger.debug("HashChainProof is "+hashChainProof+" transcation id is "+ tid); updateJSON("add", PAYMENTS_PATH + "BNK00.json", tempArray.toString()); } else { updateQuorum(quorumArray, null, false, type); @@ -685,3 +715,5 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON return APIResponse; } } + +//stakedDIDs diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 1a10d6fb..3d8793ba 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1,6 +1,11 @@ package com.rubix.Resources; import static com.rubix.Resources.APIHandler.addPublicData; +import static com.rubix.Resources.Functions.LOGGER_PATH; +import static com.rubix.Resources.Functions.calculateHash; +import static com.rubix.Resources.Functions.deleteFile; +import static com.rubix.Resources.Functions.formatAmount; +import static com.rubix.Resources.Functions.writeToFile; import static com.rubix.Resources.IPFSNetwork.IPFSNetworkLogger; import static com.rubix.Resources.IPFSNetwork.checkSwarmConnect; import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; @@ -1905,5 +1910,75 @@ public static void ownerIdentity(JSONArray tokens, String receiverDidIpfsHash) } + + public static int multiplePinCheck(String senderDidIpfsHash,JSONObject tokenObject, IPFS ipfs) throws JSONException, InterruptedException { + int statusCode = 200; + FunctionsLogger.debug("Input tokenObject is "+tokenObject.toString()); + JSONObject TokenDetails = tokenObject.getJSONObject("tokenDetails"); + JSONArray wholeTokens = TokenDetails.getJSONArray("whole-tokens"); + JSONArray wholeTokenChains = TokenDetails.getJSONArray("whole-tokenChains"); + + JSONArray partTokens = TokenDetails.getJSONArray("part-tokens"); + JSONObject partTokenChains = TokenDetails.getJSONObject("part-tokenChains"); + JSONArray partTokenChainsHash = TokenDetails.getJSONArray("hashSender"); + + JSONArray previousSendersArray = tokenObject.getJSONArray("previousSender"); + JSONArray positionsArray = tokenObject.getJSONArray("positions"); + + Double amount = tokenObject.getDouble("amount"); + JSONObject amountLedger = tokenObject.getJSONObject("amountLedger"); + FunctionsLogger.debug("Amount Ledger: " + amountLedger); + int intPart = wholeTokens.length(); + // ? multiple pin check starts + Double decimalPart = formatAmount(amount - intPart); + JSONArray doubleSpentToken = new JSONArray(); + boolean tokenOwners = true; + ArrayList pinOwnersArray = new ArrayList(); + ArrayList previousSender = new ArrayList(); + JSONArray ownersReceived = new JSONArray(); + + ArrayList ownersArray = new ArrayList(); + for (int i = 0; i < wholeTokens.length(); ++i) { + try { + FunctionsLogger.debug("Checking owners for " + wholeTokens.getString(i) + + " Please wait..."); + pinOwnersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); + + if (pinOwnersArray.size() > 2) { + + for (int j = 0; j < previousSendersArray.length(); j++) { + if (previousSendersArray.getJSONObject(j).getString("token") + .equals(wholeTokens.getString(i))) + ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); + } + + for (int j = 0; j < ownersReceived.length(); j++) { + previousSender.add(ownersReceived.getString(j)); + } + FunctionsLogger.debug("Previous Owners: " + previousSender); + + for (int j = 0; j < pinOwnersArray.size(); j++) { + if (!previousSender.contains(pinOwnersArray.get(j).toString())) + tokenOwners = false; + } + } + } catch (IOException e) { + + FunctionsLogger.debug("Ipfs dht find did not execute"); + } + } + if (!tokenOwners) { + JSONArray owners = new JSONArray(); + for (int i = 0; i < pinOwnersArray.size(); i++) + owners.put(pinOwnersArray.get(i).toString()); + FunctionsLogger.debug("Multiple Owners for " + doubleSpentToken); + FunctionsLogger.debug("Owners: " + owners); + statusCode = 420; + + return statusCode; + } + + return statusCode; + } } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 030e5182..38e21588 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -1,41 +1,7 @@ package com.rubix.TokenTransfer; -import static com.rubix.Constants.MiningConstants.MINE_ID; -import static com.rubix.Constants.MiningConstants.MINE_ID_SIGN; -import static com.rubix.Constants.MiningConstants.STAKED_QUORUM_DID; -import static com.rubix.Constants.MiningConstants.STAKED_TOKEN; -import static com.rubix.Constants.MiningConstants.STAKED_TOKEN_SIGN; -import static com.rubix.Constants.MiningConstants.STAKE_DATA; -import static com.rubix.Resources.Functions.DATA_PATH; -import static com.rubix.Resources.Functions.FunctionsLogger; -import static com.rubix.Resources.Functions.IPFS_PORT; -import static com.rubix.Resources.Functions.LOGGER_PATH; -import static com.rubix.Resources.Functions.PAYMENTS_PATH; -import static com.rubix.Resources.Functions.RECEIVER_PORT; -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.formatAmount; -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.readFile; -import static com.rubix.Resources.Functions.strToIntArray; -import static com.rubix.Resources.Functions.syncDataTable; -import static com.rubix.Resources.Functions.updateJSON; -import static com.rubix.Resources.Functions.writeToFile; -import static com.rubix.Resources.IPFSNetwork.add; -import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; -import static com.rubix.Resources.IPFSNetwork.get; -import static com.rubix.Resources.IPFSNetwork.listen; -import static com.rubix.Resources.IPFSNetwork.pin; -import static com.rubix.Resources.IPFSNetwork.repo; -import static com.rubix.Resources.IPFSNetwork.swarmConnectP2P; +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.IPFSNetwork.*; import java.awt.image.BufferedImage; import java.io.BufferedReader; @@ -55,10 +21,10 @@ import com.rubix.AuthenticateNode.Authenticate; import com.rubix.AuthenticateNode.PropImage; -import com.rubix.Constants.MiningConstants; import com.rubix.Ping.VerifyStakedToken; import com.rubix.Resources.Functions; import com.rubix.Resources.IPFSNetwork; +import com.rubix.Constants.MiningConstants.*; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; @@ -66,1153 +32,1155 @@ import org.json.JSONException; import org.json.JSONObject; +import com.rubix.Constants.*; + import io.ipfs.api.IPFS; public class TokenReceiver { - public static Logger TokenReceiverLogger = Logger.getLogger(TokenReceiver.class); - - private static final JSONObject APIResponse = new JSONObject(); - private static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); - private static String SenWalletBin; - - // token limit for each level - private static final int[] tokenLimit = { 0, 5000000, 2425000, 2303750, 2188563, 2079134, 1975178, 1876419, 1782598, - 1693468, 1608795, 1528355, 1451937, 1379340 }; - - /** - * Receiver Node: To receive a valid token from an authentic sender - * - * @return Transaction Details (JSONObject) - * @throws IOException handles IO Exceptions - * @throws JSONException handles JSON Exceptions - */ - public static String receive() { - pathSet(); - ServerSocket ss = null; - Socket sk = null; - String senderPeerID = null; - - try { - repo(ipfs); - String PART_TOKEN_CHAIN_PATH = TOKENCHAIN_PATH.concat("PARTS/"); - String PART_TOKEN_PATH = TOKENS_PATH.concat("PARTS/"); - File partFolder = new File(PART_TOKEN_PATH); - if (!partFolder.exists()) - partFolder.mkdir(); - partFolder = new File(PART_TOKEN_CHAIN_PATH); - if (!partFolder.exists()) - partFolder.mkdir(); - File partTokensFile = new File(PAYMENTS_PATH.concat("PartsToken.json")); - if (!partTokensFile.exists()) { - partTokensFile.createNewFile(); - writeToFile(partTokensFile.toString(), "[]", false); - } - - int quorumSignVerifyCount = 0; - JSONObject quorumSignatures = null; - - ArrayList quorumDID = new ArrayList<>(); - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - - String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); - - String receiverDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", receiverPeerID); - - listen(receiverPeerID, RECEIVER_PORT); - ss = new ServerSocket(RECEIVER_PORT); - TokenReceiverLogger.debug("Receiver Listening on " + RECEIVER_PORT + " appname " + receiverPeerID); - - sk = ss.accept(); - TokenReceiverLogger.debug("Data Incoming..."); - BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); - PrintStream output = new PrintStream(sk.getOutputStream()); - long startTime = System.currentTimeMillis(); - - try { - senderPeerID = input.readLine(); - } catch (SocketException e) { - TokenReceiverLogger.warn("Sender Stream Null - Sender Details"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - Sender Details"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - - TokenReceiverLogger.debug("Data Received: " + senderPeerID); - swarmConnectP2P(senderPeerID, ipfs); - - String senderDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", senderPeerID); - String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "peerid", senderPeerID); - - if (!(senderDidIpfsHash.contains("Qm") && senderWidIpfsHash.contains("Qm"))) { - output.println("420"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender details not available in network , please sync"); - TokenReceiverLogger.info("Sender details not available in datatable"); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - - nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); - File senderDIDFile = new File(DATA_PATH + senderDidIpfsHash + "/DID.png"); - if (!senderDIDFile.exists()) { - output.println("420"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender details not available"); - TokenReceiverLogger.info("Sender details not available"); - /* executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); */ - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - TokenReceiverLogger.debug("Sender details authenticated"); - output.println("200"); - - String tokenDetails; - try { - tokenDetails = input.readLine(); - } catch (SocketException e) { - TokenReceiverLogger.warn("Sender Stream Null - Token Details"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - Token Details"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - JSONObject tokenObject = new JSONObject(tokenDetails); - JSONObject TokenDetails = tokenObject.getJSONObject("tokenDetails"); - JSONArray wholeTokens = TokenDetails.getJSONArray("whole-tokens"); - JSONArray wholeTokenChains = TokenDetails.getJSONArray("whole-tokenChains"); - - JSONArray partTokens = TokenDetails.getJSONArray("part-tokens"); - JSONObject partTokenChains = TokenDetails.getJSONObject("part-tokenChains"); - JSONArray partTokenChainsHash = TokenDetails.getJSONArray("hashSender"); - - JSONArray previousSendersArray = tokenObject.getJSONArray("previousSender"); - JSONArray positionsArray = tokenObject.getJSONArray("positions"); - - Double amount = tokenObject.getDouble("amount"); - JSONObject amountLedger = tokenObject.getJSONObject("amountLedger"); - TokenReceiverLogger.debug("Amount Ledger: " + amountLedger); - int intPart = wholeTokens.length(); - // ? multiple pin check starts - Double decimalPart = formatAmount(amount - intPart); - JSONArray doubleSpentToken = new JSONArray(); - boolean tokenOwners = true; - ArrayList pinOwnersArray = new ArrayList(); - ArrayList previousSender = new ArrayList(); - JSONArray ownersReceived = new JSONArray(); - for (int i = 0; i < wholeTokens.length(); ++i) { - try { - TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + - " Please wait..."); - pinOwnersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); - - if (pinOwnersArray.size() > 2) { - - for (int j = 0; j < previousSendersArray.length(); j++) { - if (previousSendersArray.getJSONObject(j).getString("token") - .equals(wholeTokens.getString(i))) - ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); - } - - for (int j = 0; j < ownersReceived.length(); j++) { - previousSender.add(ownersReceived.getString(j)); - } - TokenReceiverLogger.debug("Previous Owners: " + previousSender); - - for (int j = 0; j < pinOwnersArray.size(); j++) { - if (!previousSender.contains(pinOwnersArray.get(j).toString())) - tokenOwners = false; - } - } - } catch (IOException e) { - - TokenReceiverLogger.debug("Ipfs dht find did not execute"); - } - } - if (!tokenOwners) { - JSONArray owners = new JSONArray(); - for (int i = 0; i < pinOwnersArray.size(); i++) - owners.put(pinOwnersArray.get(i).toString()); - TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); - TokenReceiverLogger.debug("Owners: " + owners); - output.println("420"); - output.println(doubleSpentToken.toString()); - output.println(owners.toString()); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + - owners); - IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - // ? multiple pin check ends - String senderToken = TokenDetails.toString(); - String consensusID = calculateHash(senderToken, "SHA3-256"); - writeToFile(LOGGER_PATH + "consensusID", consensusID, false); - String consensusIDIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "consensusID", ipfs); - deleteFile(LOGGER_PATH + "consensusID"); - - if (!IPFSNetwork.dhtEmpty(consensusIDIPFSHash, ipfs)) { - TokenReceiverLogger.debug("consensus ID not unique" + consensusIDIPFSHash); - output.println("421"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Consensus ID not unique"); - IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - - // Check IPFS get for all Tokens - int ipfsGetFlag = 0; - ArrayList wholeTokenContent = new ArrayList<>(); - ArrayList wholeTokenChainContent = new ArrayList<>(); - for (int i = 0; i < intPart; i++) { - String TokenChainContent = get(wholeTokenChains.getString(i), ipfs); - wholeTokenChainContent.add(TokenChainContent); - String TokenContent = get(wholeTokens.getString(i), ipfs); - wholeTokenContent.add(TokenContent); - ipfsGetFlag++; - } - repo(ipfs); - - if (!(ipfsGetFlag == intPart)) { - output.println("422"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - 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(); - ss.close(); - return APIResponse.toString(); - } - - JSONArray partTokenChainContent = new JSONArray(); - JSONArray partTokenContent = new JSONArray(); - - for (int i = 0; i < partTokenChains.length(); i++) { - - partTokenChainContent.put(partTokenChains.getJSONArray(partTokens.getString(i))); - String TokenContent = get(partTokens.getString(i), ipfs); - partTokenContent.put(TokenContent); - } - - boolean chainFlag = true; - for (int i = 0; i < partTokenChainContent.length(); i++) { - JSONArray tokenChainContent = partTokenChainContent.getJSONArray(i); - for (int j = 0; j < tokenChainContent.length(); j++) { - String previousHash = tokenChainContent.getJSONObject(j).getString("previousHash"); - String nextHash = tokenChainContent.getJSONObject(j).getString("nextHash"); - String rePreviousHash, reNextHash; - if (tokenChainContent.length() > 1) { - if (j == 0) { - rePreviousHash = ""; - String rePrev = calculateHash(new JSONObject().toString(), "SHA3-256"); - reNextHash = calculateHash(tokenChainContent.getJSONObject(j + 1).getString("tid"), - "SHA3-256"); - - if (!((rePreviousHash.equals(previousHash) || rePrev.equals(previousHash)) - && reNextHash.equals(nextHash))) { - chainFlag = false; - } - - } else if (j == tokenChainContent.length() - 1) { - rePreviousHash = calculateHash(tokenChainContent.getJSONObject(j - 1).getString("tid"), - "SHA3-256"); - reNextHash = ""; - - if (!(rePreviousHash.equals(previousHash) && reNextHash.equals(nextHash))) { - chainFlag = false; - } - - } else { - rePreviousHash = calculateHash(tokenChainContent.getJSONObject(j - 1).getString("tid"), - "SHA3-256"); - reNextHash = calculateHash(tokenChainContent.getJSONObject(j + 1).getString("tid"), - "SHA3-256"); - - if (!(rePreviousHash.equals(previousHash) && reNextHash.equals(nextHash))) { - chainFlag = false; - } - } - } - } - } - - if (!chainFlag) { - String errorMessage = "Broken Cheque Chain"; - output.println("423"); - 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(); - } - - boolean ownerCheck = true; - - JSONArray allTokens = new JSONArray(); - for (int i = 0; i < wholeTokens.length(); i++) - allTokens.put(wholeTokens.getString(i)); - for (int i = 0; i < partTokens.length(); i++) - allTokens.put(partTokens.getString(i)); - - JSONArray allTokensChains = new JSONArray(); - for (int i = 0; i < wholeTokenChainContent.size(); i++) - allTokensChains.put(wholeTokenChainContent.get(i)); - for (int i = 0; i < partTokenChainContent.length(); i++) - allTokensChains.put(partTokenChainContent.get(i)); - - JSONArray invalidTokens = new JSONArray(); - - for (int count = 0; count < wholeTokens.length(); count++) { - - String tokens = null; - JSONArray tokenChain = new JSONArray(wholeTokens.get(count).toString()); - String TokenContent = get(wholeTokens.getString(count), ipfs); - String tokenLevel = TokenContent.substring(0, TokenContent.length() - 64); - String tokenNumberHash = TokenContent.substring(TokenContent.length() - 64); - // String tokenLevel = TokenContent.substring(0, 3); - // String tokenNumberHash = TokenContent.substring(3, - // TokenContent.indexOf("\n")); - - int tokenLevelInt = Integer.parseInt(tokenLevel); - int tokenLimitForLevel = tokenLimit[tokenLevelInt]; - int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); - int minumumStakeHeight = tokenLevelValue * 4; - int tokenNumber = 1204401; - - // check TokenHashTable exists - File tokenHashTable = new File( - WALLET_DATA_PATH.concat("TokenHashTable").concat(".json")); - if (!tokenHashTable.exists()) { - tokenHashTable.createNewFile(); - JSONObject tokenHashTableJSON = new JSONObject(); - for (int i = 1; i <= 5000000; i++) { - tokenHashTableJSON.put(calculateHash(String.valueOf(i), "SHA-256"), i); - } - writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); - } - String tokenHashTableData = readFile(tokenHashTable.toString()); - JSONObject tokenHashTableJSON = new JSONObject(tokenHashTableData); - if (tokenHashTableJSON.has(tokenNumberHash)) { - tokenNumber = tokenHashTableJSON.getInt(tokenNumberHash); - TokenReceiverLogger.debug("Token Number: " + tokenNumber); - if (tokenNumber > tokenLimitForLevel) { - String errorMessage = "Token Number is greater than Token Limit for the Level"; - output.println("426"); - 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 { - TokenReceiverLogger.debug("Invalid Content Found in Token : " + tokenNumberHash); - String errorMessage = "Invalid Content Found in Token"; - output.println("426"); - 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(); - } - - // ! check quorum signs for previous transaction for the tokenchain to verify - // ! the ownership of sender for the token - - if ((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { - - JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); - TokenReceiverLogger.debug("Last Object = " + lastObject); - - if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { - - TokenReceiverLogger.debug("Checking ownership"); - String owner = lastObject.getString("owner"); - tokens = allTokens.getString(count); - String hashString = tokens.concat(senderDidIpfsHash); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); - String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); - - TokenReceiverLogger.debug("Ownership Here Sender Calculation"); - TokenReceiverLogger.debug("tokens: " + tokens); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); - - if (!owner.equals(ownerRecalculated)) { - ownerCheck = false; - invalidTokens.put(tokens); - } - - if (ownerCheck && (tokenChain.length() < minumumStakeHeight)) { - // && (tokenNumber > 1204400) - JSONObject genesiObject = tokenChain.getJSONObject(0); - JSONArray stakeDataArray = genesiObject.getJSONArray(MINE_ID); - - int randomNumber = new Random().nextInt(15); - JSONObject genesisSignaturesContent = genesiObject - .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); - Iterator randomKey = genesisSignaturesContent.keys(); - for (int i = 0; i < randomNumber; i++) { - randomKey.next(); - } - /** - * String randomKeyString = randomKey.next().toString(); - * JSONObject verificationPick = new JSONObject(); - * verificationPick.put("did", randomKeyString); - * verificationPick.put("hash", genesiObject.getString("tid")); - * verificationPick.put("signature", - * genesisSignaturesContent.getString(randomKeyString)); - * - * if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) - * { - * - * if (Authenticate.verifySignature(verificationPick.toString())) { - * TokenReceiverLogger.debug("Staking check (3) successful"); - * } else { - * TokenReceiverLogger.debug( - * "Staking check (3) failed: Could not verify genesis credit signature"); - * ownerCheck = false; - * invalidTokens.put(tokens); - * } - * } else { - * TokenReceiverLogger.debug( - * "Staking check (3) failed: Genesis TID is not equal to the hash of the - * genesis signature"); - * ownerCheck = false; - * invalidTokens.put(tokens); - * } - */ - // else { - // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not - // found"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - - if (stakeDataArray.length() == 3) { - - JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); - JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); - JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); - - String[] stakedTokenTC = new String[3]; - String[] stakedTokenSignTC = new String[3]; - String[] stakerDIDTC = new String[3]; - String[] mineIDTC = new String[3]; - String[] mineIDSignTC = new String[3]; - - stakedTokenTC[0] = oneOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[0] = oneOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[0] = oneOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[0] = oneOfThreeStake.getString(MINE_ID); - mineIDSignTC[0] = oneOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[1] = twoOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[1] = twoOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[1] = twoOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[1] = twoOfThreeStake.getString(MINE_ID); - mineIDSignTC[1] = twoOfThreeStake.getString(MINE_ID_SIGN); - - stakedTokenTC[2] = threeOfThreeStake.getString(STAKED_TOKEN); - stakedTokenSignTC[2] = threeOfThreeStake.getString(STAKED_TOKEN_SIGN); - stakerDIDTC[2] = threeOfThreeStake.getString(STAKED_QUORUM_DID); - mineIDTC[2] = threeOfThreeStake.getString(MINE_ID); - mineIDSignTC[2] = threeOfThreeStake.getString(MINE_ID_SIGN); - - for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { - - String mineIDContent = get(mineIDTC[stakeCount], ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - TokenReceiverLogger.debug(mineIDContentJSON.toString()); - - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - - String stakerDIDMineData = stakeData.getString(STAKED_QUORUM_DID); - String stakedTokenMineData = stakeData.getString(STAKED_TOKEN); - String stakedTokenSignMineData = stakeData.getString(STAKED_TOKEN_SIGN); - - TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); - TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); - - TokenReceiverLogger.debug(stakerDIDMineData); - TokenReceiverLogger.debug(stakedTokenMineData); - TokenReceiverLogger.debug(stakedTokenSignMineData); - - if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) - && stakedTokenTC[stakeCount].equals(stakedTokenMineData) - && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { - - JSONObject detailsToVerify = new JSONObject(); - detailsToVerify.put("did", stakerDIDTC[stakeCount]); - detailsToVerify.put("hash", mineIDTC[stakeCount]); - detailsToVerify.put("signature", mineIDSignTC[stakeCount]); - if (Authenticate.verifySignature(detailsToVerify.toString())) { - - boolean minedTokenStatus = true; - ArrayList ownersArray = IPFSNetwork - .dhtOwnerCheck(stakedTokenTC[stakeCount]); - for (int i = 0; i < ownersArray.size(); i++) { - if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { - minedTokenStatus = false; - } - } - if (!minedTokenStatus) { - TokenReceiverLogger.debug( - "Staked token is not found with staker DID: " - + stakerDIDTC[stakeCount]); - ownerCheck = false; - invalidTokens.put(tokens); - } - - } else { - TokenReceiverLogger.debug( - "Staking check (2) failed - unable to verify mine ID signature by staker: " - + stakerDIDTC[stakeCount]); - ownerCheck = false; - invalidTokens.put(tokens); - } - - TokenReceiverLogger - .debug("MineID Verification Successful with Staking node: " - + stakerDIDTC[stakeCount]); - } else { - TokenReceiverLogger.debug("Staking check (2) failed"); - ownerCheck = false; - invalidTokens.put(tokens); - } - - TokenReceiverLogger.debug("Staking check (2) successful"); - // } else { - // TokenReceiverLogger.debug( - // "Staking check (2) failed: Could not verify mine ID signature"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - } - - } else { - ownerCheck = false; - TokenReceiverLogger.debug("Staked Token is not available!"); - - } - - } - } - if (lastObject.has(MiningConstants.STAKED_TOKEN)) { - - Boolean minedTokenStatus = true; - - String mineID = lastObject.getString(MINE_ID); - - String mineIDContent = get(mineID, ipfs); - JSONObject mineIDContentJSON = new JSONObject(mineIDContent); - - JSONObject stakeData = mineIDContentJSON.getJSONObject(STAKE_DATA); - - ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakeData.getString(STAKED_TOKEN)); - for (int i = 0; i < ownersArray.size(); i++) { - if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - stakeData.getString( - STAKED_TOKEN), - mineIDContentJSON.getString("tokenContent"))) { - minedTokenStatus = false; - } - } - if (!minedTokenStatus) { - TokenReceiverLogger - .debug("Staking check failed: Found staked token but token height < 46"); - ownerCheck = false; - invalidTokens.put(tokens); - } - - TokenReceiverLogger.debug( - "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); - ownerCheck = false; - invalidTokens.put(tokens); - - // JSONObject tokenToVerify = new JSONObject(); - // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { - - // JSONObject stakeData = - // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); - // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); - // String stakedToken = stakeData.getString(STAKED_TOKEN); - // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); - - // tokenToVerify.put("did", senderDidIpfsHash); - // tokenToVerify.put("hash", stakedToken); - // tokenToVerify.put("signature", stakedTokenSign); - - // if (Authenticate.verifySignature(tokenToVerify.toString())) { - - // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); - // for (int i = 0; i < ownersArray.size(); i++) { - // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, - // mineIDContentJSON.getString("tokenContent"))) { - // minedTokenStatus = false; - // } - // } - // if (!minedTokenStatus) { - // TokenReceiverLogger - // .debug("Staking check failed: Found staked token but token height < 46"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - - // TokenReceiverLogger.debug( - // "Staking check failed: Found staked token but unable to transfer while mined - // token height is not satisfied for the network"); - // ownerCheck = false; - // invalidTokens.put(tokens); - - // } else { - // TokenReceiverLogger.debug( - // "Staking check failed: Found staked token but unable to verify staked token - // height"); - // ownerCheck = false; - // invalidTokens.put(tokens); - // } - // } - - } - } - } - - if (!ownerCheck) { - TokenReceiverLogger.debug("Ownership Check Failed"); - String errorMessage = "Ownership Check Failed"; - output.println("424"); - output.println(invalidTokens.toString()); - 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 - TokenReceiverLogger.debug("Ownership Check Passed"); - - boolean partsAvailable = true; - for (int i = 0; i < partTokenChainContent.length(); i++) { - Double senderCount = 0.000D, receiverCount = 0.000D; - JSONArray tokenChainContent = partTokenChainContent.getJSONArray(i); - for (int k = 0; k < tokenChainContent.length(); k++) { - if (tokenChainContent.getJSONObject(k).has("role")) { - if (tokenChainContent.getJSONObject(k).getString("role").equals("Sender") - && tokenChainContent.getJSONObject(k).getString("sender").equals(senderDidIpfsHash)) { - senderCount += tokenChainContent.getJSONObject(k).getDouble("amount"); - } else if (tokenChainContent.getJSONObject(k).getString("role").equals("Receiver") - && tokenChainContent.getJSONObject(k).getString("receiver").equals(senderDidIpfsHash)) { - receiverCount += tokenChainContent.getJSONObject(k).getDouble("amount"); - } - } - } - FunctionsLogger.debug("Sender Parts: " + formatAmount(senderCount)); - FunctionsLogger.debug("Receiver Parts: " + formatAmount(receiverCount)); - Double availableParts = receiverCount - senderCount; - - availableParts = formatAmount(availableParts); - availableParts += amountLedger.getDouble(partTokens.getString(i)); - availableParts = formatAmount(availableParts); - - if (availableParts > 1.000D) { - TokenReceiverLogger.debug("Token wholly spent: " + partTokens.getString(i)); - TokenReceiverLogger.debug("Parts: " + availableParts); - partsAvailable = false; - } - } - if (!partsAvailable) { - String errorMessage = "Token wholly spent already"; - output.println("425"); - 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(); - } - output.println("200"); - - String senderDetails; - try { - senderDetails = input.readLine(); - } catch (SocketException e) { - TokenReceiverLogger.warn("Sender Stream Null - Sender Details"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - Sender Details"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - JSONObject SenderDetails = new JSONObject(senderDetails); - String senderSignature = SenderDetails.getString("sign"); - String tid = SenderDetails.getString("tid"); - String comment = SenderDetails.getString("comment"); - String Status = SenderDetails.getString("status"); - String QuorumDetails = SenderDetails.getString("quorumsign"); - - BufferedImage senderWidImage = ImageIO.read(new File(DATA_PATH + senderDidIpfsHash + "/PublicShare.png")); - SenWalletBin = PropImage.img2bin(senderWidImage); - - 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")) { - quorumSignatures = new JSONObject(QuorumDetails); - String selectQuorumHash = calculateHash(senderToken, "SHA3-256"); - String verifyQuorumHash = calculateHash(selectQuorumHash.concat(receiverDidIpfsHash), "SHA3-256"); - - Iterator keys = quorumSignatures.keys(); - while (keys.hasNext()) { - String key = keys.next(); - quorumDID.add(key); - } - - for (String quorumDidIpfsHash : quorumDID) { - syncDataTable(quorumDidIpfsHash, null); - String quorumWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", - quorumDidIpfsHash); - - nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); - } - - for (int i = 0; i < quorumSignatures.length(); i++) { - - JSONObject detailsForVerify = new JSONObject(); - detailsForVerify.put("did", quorumDID.get(i)); - detailsForVerify.put("hash", verifyQuorumHash); - detailsForVerify.put("signature", quorumSignatures.getString(quorumDID.get(i))); - boolean val = Authenticate.verifySignature(detailsForVerify.toString()); - if (val) - quorumSignVerifyCount++; - } - TokenReceiverLogger.debug("Verified Quorum Count " + quorumSignVerifyCount); - yesQuorum = quorumSignVerifyCount >= quorumSignatures.length(); - } - JSONArray wholeTokenChainHash = new JSONArray(); - for (int i = 0; i < intPart; i++) - wholeTokenChainHash.put(wholeTokenChains.getString(i)); - - String hash = calculateHash( - wholeTokens.toString() + wholeTokenChainHash.toString() + partTokens.toString() - + partTokenChainsHash.toString() + receiverDidIpfsHash + senderDidIpfsHash + comment, - "SHA3-256"); - TokenReceiverLogger.debug("Hash to verify Sender: " + hash); - JSONObject detailsForVerify = new JSONObject(); - detailsForVerify.put("did", senderDidIpfsHash); - detailsForVerify.put("hash", hash); - 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); - APIResponse.put("tid", tid); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender / Quorum not verified"); - TokenReceiverLogger.info("Sender / Quorum not verified"); - IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - - repo(ipfs); - TokenReceiverLogger.debug("Sender and Quorum Verified"); - output.println("200"); - - String pinDetails; - try { - pinDetails = input.readLine(); - } catch (SocketException e) { - TokenReceiverLogger.warn("Sender Stream Null - Pinning Status"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - Pinning Status"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - if (pinDetails.equals("Unpinned")) { - int count = 0; - for (int i = 0; i < intPart; i++) { - FileWriter fileWriter; - fileWriter = new FileWriter(TOKENS_PATH + wholeTokens.getString(i)); - fileWriter.write(wholeTokenContent.get(i)); - fileWriter.close(); - add(TOKENS_PATH + wholeTokens.getString(i), ipfs); - pin(wholeTokens.getString(i), ipfs); - count++; - - } - - for (int i = 0; i < partTokens.length(); i++) { - File tokenFile = new File(PART_TOKEN_PATH + partTokens.getString(i)); - if (!tokenFile.exists()) - tokenFile.createNewFile(); - FileWriter fileWriter; - fileWriter = new FileWriter(PART_TOKEN_PATH + partTokens.getString(i)); - fileWriter.write(partTokenContent.getString(i)); - fileWriter.close(); - String tokenHash = add(PART_TOKEN_PATH + partTokens.getString(i), ipfs); - pin(tokenHash, ipfs); - - } - - if (count == intPart) { - TokenReceiverLogger.debug("Pinned All Tokens"); - output.println("Successfully Pinned"); - - String essentialShare; - try { - essentialShare = input.readLine(); - } catch (SocketException e) { - TokenReceiverLogger.warn("Sender Stream Null - EShare Details"); - APIResponse.put("did", ""); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender Stream Null - EShare Details"); - - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - long endTime = System.currentTimeMillis(); - for (int i = 0; i < intPart; i++) { - String tokens = wholeTokens.getString(i); - String hashString = tokens.concat(receiverDidIpfsHash); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - - BufferedImage pvt = ImageIO - .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); - String firstPrivate = PropImage.img2bin(pvt); - int[] privateIntegerArray1 = strToIntArray(firstPrivate); - String privateBinary = Functions.intArrayToStr(privateIntegerArray1); - String positions = ""; - for (int j = 0; j < privateIntegerArray1.length; j += 49152) { - positions += privateBinary.charAt(j); - } - String ownerIdentity = hashForPositions.concat(positions); - String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); - - TokenReceiverLogger.debug("Ownership Here"); - TokenReceiverLogger.debug("tokens: " + wholeTokens.getString(i)); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positions); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); - - ArrayList groupTokens = new ArrayList<>(); - for (int k = 0; k < intPart; k++) { - if (!wholeTokens.getString(i).equals(wholeTokens.getString(k))) - groupTokens.add(wholeTokens.getString(k)); - } - - JSONArray arrToken = new JSONArray(); - JSONObject objectToken = new JSONObject(); - objectToken.put("tokenHash", wholeTokens.getString(i)); - arrToken.put(objectToken); - JSONArray arr1 = new JSONArray(wholeTokenChainContent.get(i)); - JSONObject obj2 = new JSONObject(); - obj2.put("senderSign", senderSignature); - obj2.put("sender", senderDidIpfsHash); - obj2.put("group", groupTokens); - obj2.put("comment", comment); - obj2.put("tid", tid); - obj2.put("owner", ownerIdentityHash); - arr1.put(obj2); - writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); - } - - for (int i = 0; i < partTokens.length(); i++) { - JSONObject chequeObject = new JSONObject(); - chequeObject.put("sender", senderDidIpfsHash); - chequeObject.put("receiver", receiverDidIpfsHash); - chequeObject.put("parent-token", partTokens.getString(i)); - chequeObject.put("parent-chain", partTokenChains.getJSONArray(partTokens.getString(i))); - Double partAmount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); - chequeObject.put("amount", partAmount); - chequeObject.put("tid", tid); - - writeToFile(LOGGER_PATH.concat(partTokens.getString(i)), chequeObject.toString(), false); - String chequeHash = IPFSNetwork.add(LOGGER_PATH.concat(partTokens.getString(i)), ipfs); - deleteFile(LOGGER_PATH.concat(partTokens.getString(i))); - - String tokens = partTokens.getString(i); - String hashString = tokens.concat(receiverDidIpfsHash); - String hashForPositions = calculateHash(hashString, "SHA3-256"); - BufferedImage pvt = ImageIO - .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); - String firstPrivate = PropImage.img2bin(pvt); - int[] privateIntegerArray1 = strToIntArray(firstPrivate); - String privateBinary = Functions.intArrayToStr(privateIntegerArray1); - String positions = ""; - for (int j = 0; j < privateIntegerArray1.length; j += 49152) { - positions += privateBinary.charAt(j); - } - - String ownerIdentity = hashForPositions.concat(positions); - String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); - - TokenReceiverLogger.debug("Ownership Here"); - TokenReceiverLogger.debug("tokens: " + partTokens.getString(i)); - TokenReceiverLogger.debug("hashString: " + hashString); - TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); - TokenReceiverLogger.debug("p1: " + positions); - TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); - TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); - - JSONObject newPartObject = new JSONObject(); - newPartObject.put("senderSign", senderSignature); - newPartObject.put("sender", senderDidIpfsHash); - newPartObject.put("receiver", receiverDidIpfsHash); - newPartObject.put("comment", comment); - newPartObject.put("tid", tid); - newPartObject.put("nextHash", ""); - newPartObject.put("owner", ownerIdentityHash); - if (partTokenChainContent.getJSONArray(i).length() == 0) - newPartObject.put("previousHash", ""); - else - newPartObject.put("previousHash", - calculateHash(partTokenChainContent.getJSONArray(i) - .getJSONObject(partTokenChainContent.getJSONArray(i).length() - 1) - .getString("tid"), "SHA3-256")); - - newPartObject.put("amount", partAmount); - newPartObject.put("cheque", chequeHash); - newPartObject.put("role", "Receiver"); - - File chainFile = new File( - PART_TOKEN_CHAIN_PATH.concat(partTokens.getString(i)).concat(".json")); - if (chainFile.exists()) { - - String readChain = readFile(PART_TOKEN_CHAIN_PATH + partTokens.getString(i) + ".json"); - JSONArray readChainArray = new JSONArray(readChain); - readChainArray.put(partTokenChainContent.getJSONArray(i) - .getJSONObject(partTokenChainContent.getJSONArray(i).length() - 1)); - readChainArray.put(newPartObject); - - writeToFile(PART_TOKEN_CHAIN_PATH + partTokens.getString(i) + ".json", - readChainArray.toString(), false); - - } else { - partTokenChainContent.getJSONArray(i).put(newPartObject); - writeToFile(PART_TOKEN_CHAIN_PATH + partTokens.getString(i) + ".json", - partTokenChainContent.getJSONArray(i).toString(), false); - } - } - - JSONObject transactionRecord = new JSONObject(); - transactionRecord.put("role", "Receiver"); - transactionRecord.put("tokens", allTokens); - transactionRecord.put("txn", tid); - transactionRecord.put("quorumList", quorumSignatures.keys()); - transactionRecord.put("senderDID", senderDidIpfsHash); - transactionRecord.put("receiverDID", receiverDidIpfsHash); - transactionRecord.put("Date", getCurrentUtcTime()); - transactionRecord.put("totalTime", (endTime - startTime)); - transactionRecord.put("comment", comment); - transactionRecord.put("essentialShare", essentialShare); - amount = formatAmount(amount); - transactionRecord.put("amount-received", amount); - - JSONArray transactionHistoryEntry = new JSONArray(); - transactionHistoryEntry.put(transactionRecord); - updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", - transactionHistoryEntry.toString()); - - for (int i = 0; i < wholeTokens.length(); i++) { - String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray bankArray = new JSONArray(bankFile); - JSONObject tokenObject1 = new JSONObject(); - tokenObject1.put("tokenHash", wholeTokens.getString(i)); - bankArray.put(tokenObject1); - Functions.writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); - - } - - String partsFile = readFile(PAYMENTS_PATH.concat("PartsToken.json")); - JSONArray partsReadArray = new JSONArray(partsFile); - - for (int i = 0; i < partTokens.length(); i++) { - boolean writeParts = true; - for (int j = 0; j < partsReadArray.length(); j++) { - if (partsReadArray.getJSONObject(j).getString("tokenHash") - .equals(partTokens.getString(i))) - writeParts = false; - } - if (writeParts) { - JSONObject partObject = new JSONObject(); - partObject.put("tokenHash", partTokens.getString(i)); - partsReadArray.put(partObject); - } - } - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partsReadArray.toString(), false); - - TokenReceiverLogger.info("Transaction ID: " + tid + "Transaction Successful"); - output.println("Send Response"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", tid); - APIResponse.put("status", "Success"); - APIResponse.put("tokens", wholeTokens); - APIResponse.put("comment", comment); - APIResponse.put("message", "Transaction Successful"); - TokenReceiverLogger.info(" Transaction Successful"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - output.println("count mistmatch"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "count mismacth"); - TokenReceiverLogger.info(" Transaction failed"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Failed to unpin"); - TokenReceiverLogger.info(" Transaction failed"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Consensus failed at Sender side"); - TokenReceiverLogger.info(" Transaction failed"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - - } catch ( - - Exception e) { - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - TokenReceiverLogger.error("Exception Occurred", e); - return APIResponse.toString(); - } finally { - try { - ss.close(); - sk.close(); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - } catch (Exception e) { - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - TokenReceiverLogger.error("Exception Occurred", e); - } - - } - } + public static Logger TokenReceiverLogger = Logger.getLogger(TokenReceiver.class); + + private static final JSONObject APIResponse = new JSONObject(); + private static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + private static String SenWalletBin; + + // token limit for each level + private static final int[] tokenLimit = { 0, 5000000, 2425000, 2303750, 2188563, 2079134, 1975178, 1876419, 1782598, + 1693468, 1608795, 1528355, 1451937, 1379340 }; + + /** + * Receiver Node: To receive a valid token from an authentic sender + * + * @return Transaction Details (JSONObject) + * @throws IOException handles IO Exceptions + * @throws JSONException handles JSON Exceptions + */ + public static String receive() { + pathSet(); + ServerSocket ss = null; + Socket sk = null; + String senderPeerID = null; + + try { + repo(ipfs); + String PART_TOKEN_CHAIN_PATH = TOKENCHAIN_PATH.concat("PARTS/"); + String PART_TOKEN_PATH = TOKENS_PATH.concat("PARTS/"); + File partFolder = new File(PART_TOKEN_PATH); + if (!partFolder.exists()) + partFolder.mkdir(); + partFolder = new File(PART_TOKEN_CHAIN_PATH); + if (!partFolder.exists()) + partFolder.mkdir(); + File partTokensFile = new File(PAYMENTS_PATH.concat("PartsToken.json")); + if (!partTokensFile.exists()) { + partTokensFile.createNewFile(); + writeToFile(partTokensFile.toString(), "[]", false); + } + + int quorumSignVerifyCount = 0; + JSONObject quorumSignatures = null; + + ArrayList quorumDID = new ArrayList<>(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + String receiverPeerID = getPeerID(DATA_PATH + "DID.json"); + + String receiverDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", receiverPeerID); + + listen(receiverPeerID, RECEIVER_PORT); + ss = new ServerSocket(RECEIVER_PORT); + TokenReceiverLogger.debug("Receiver Listening on " + RECEIVER_PORT + " appname " + receiverPeerID); + + sk = ss.accept(); + TokenReceiverLogger.debug("Data Incoming..."); + BufferedReader input = new BufferedReader(new InputStreamReader(sk.getInputStream())); + PrintStream output = new PrintStream(sk.getOutputStream()); + long startTime = System.currentTimeMillis(); + + try { + senderPeerID = input.readLine(); + } catch (SocketException e) { + TokenReceiverLogger.warn("Sender Stream Null - Sender Details"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - Sender Details"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + + TokenReceiverLogger.debug("Data Received: " + senderPeerID); + swarmConnectP2P(senderPeerID, ipfs); + + String senderDidIpfsHash = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", senderPeerID); + String senderWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "peerid", senderPeerID); + + if (!(senderDidIpfsHash.contains("Qm") && senderWidIpfsHash.contains("Qm"))) { + output.println("420"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender details not available in network , please sync"); + TokenReceiverLogger.info("Sender details not available in datatable"); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + + nodeData(senderDidIpfsHash, senderWidIpfsHash, ipfs); + File senderDIDFile = new File(DATA_PATH + senderDidIpfsHash + "/DID.png"); + if (!senderDIDFile.exists()) { + output.println("420"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender details not available"); + TokenReceiverLogger.info("Sender details not available"); + /* executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); */ + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + TokenReceiverLogger.debug("Sender details authenticated"); + output.println("200"); + + String tokenDetails; + try { + tokenDetails = input.readLine(); + } catch (SocketException e) { + TokenReceiverLogger.warn("Sender Stream Null - Token Details"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - Token Details"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + JSONObject tokenObject = new JSONObject(tokenDetails); + JSONObject TokenDetails = tokenObject.getJSONObject("tokenDetails"); + JSONArray wholeTokens = TokenDetails.getJSONArray("whole-tokens"); + JSONArray wholeTokenChains = TokenDetails.getJSONArray("whole-tokenChains"); + + JSONArray partTokens = TokenDetails.getJSONArray("part-tokens"); + JSONObject partTokenChains = TokenDetails.getJSONObject("part-tokenChains"); + JSONArray partTokenChainsHash = TokenDetails.getJSONArray("hashSender"); + + JSONArray previousSendersArray = tokenObject.getJSONArray("previousSender"); + JSONArray positionsArray = tokenObject.getJSONArray("positions"); + + Double amount = tokenObject.getDouble("amount"); + JSONObject amountLedger = tokenObject.getJSONObject("amountLedger"); + TokenReceiverLogger.debug("Amount Ledger: " + amountLedger); + int intPart = wholeTokens.length(); + // ? multiple pin check starts + Double decimalPart = formatAmount(amount - intPart); + JSONArray doubleSpentToken = new JSONArray(); + boolean tokenOwners = true; + ArrayList pinOwnersArray = new ArrayList(); + ArrayList previousSender = new ArrayList(); + JSONArray ownersReceived = new JSONArray(); + TokenReceiverLogger.debug("previousSendersArray is " + previousSendersArray.toString()); + TokenReceiverLogger.debug("tokenObject is " + tokenObject.toString()); + TokenReceiverLogger.debug("tokenDetails(base for tokenObj) is " + tokenDetails.toString()); + + // previoussenderarray + // tokenobject + for (int i = 0; i < wholeTokens.length(); ++i) { + try { + TokenReceiverLogger.debug("Checking owners for " + wholeTokens.getString(i) + " Please wait..."); + pinOwnersArray = IPFSNetwork.dhtOwnerCheck(wholeTokens.getString(i)); + + if (pinOwnersArray.size() > 2) { + + for (int j = 0; j < previousSendersArray.length(); j++) { + if (previousSendersArray.getJSONObject(j).getString("token") + .equals(wholeTokens.getString(i))) + ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); + } + + for (int j = 0; j < ownersReceived.length(); j++) { + previousSender.add(ownersReceived.getString(j)); + } + TokenReceiverLogger.debug("Previous Owners: " + previousSender); + + for (int j = 0; j < pinOwnersArray.size(); j++) { + if (!previousSender.contains(pinOwnersArray.get(j).toString())) + tokenOwners = false; + } + } + } catch (IOException e) { + + TokenReceiverLogger.debug("Ipfs dht find did not execute"); + } + } + if (!tokenOwners) { + JSONArray owners = new JSONArray(); + for (int i = 0; i < pinOwnersArray.size(); i++) + owners.put(pinOwnersArray.get(i).toString()); + TokenReceiverLogger.debug("Multiple Owners for " + doubleSpentToken); + TokenReceiverLogger.debug("Owners: " + owners); + output.println("420"); + output.println(doubleSpentToken.toString()); + output.println(owners.toString()); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Multiple Owners for " + doubleSpentToken + " " + owners); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + // ? multiple pin check ends + String senderToken = TokenDetails.toString(); + String consensusID = calculateHash(senderToken, "SHA3-256"); + writeToFile(LOGGER_PATH + "consensusID", consensusID, false); + String consensusIDIPFSHash = IPFSNetwork.addHashOnly(LOGGER_PATH + "consensusID", ipfs); + deleteFile(LOGGER_PATH + "consensusID"); + + if (!IPFSNetwork.dhtEmpty(consensusIDIPFSHash, ipfs)) { + TokenReceiverLogger.debug("consensus ID not unique" + consensusIDIPFSHash); + output.println("421"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Consensus ID not unique"); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + + // Check IPFS get for all Tokens + int ipfsGetFlag = 0; + ArrayList wholeTokenContent = new ArrayList<>(); + ArrayList wholeTokenChainContent = new ArrayList<>(); + for (int i = 0; i < intPart; i++) { + String TokenChainContent = get(wholeTokenChains.getString(i), ipfs); + wholeTokenChainContent.add(TokenChainContent); + String TokenContent = get(wholeTokens.getString(i), ipfs); + wholeTokenContent.add(TokenContent); + ipfsGetFlag++; + } + repo(ipfs); + + if (!(ipfsGetFlag == intPart)) { + output.println("422"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + 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(); + ss.close(); + return APIResponse.toString(); + } + + JSONArray partTokenChainContent = new JSONArray(); + JSONArray partTokenContent = new JSONArray(); + + for (int i = 0; i < partTokenChains.length(); i++) { + + partTokenChainContent.put(partTokenChains.getJSONArray(partTokens.getString(i))); + String TokenContent = get(partTokens.getString(i), ipfs); + partTokenContent.put(TokenContent); + } + + boolean chainFlag = true; + for (int i = 0; i < partTokenChainContent.length(); i++) { + JSONArray tokenChainContent = partTokenChainContent.getJSONArray(i); + for (int j = 0; j < tokenChainContent.length(); j++) { + String previousHash = tokenChainContent.getJSONObject(j).getString("previousHash"); + String nextHash = tokenChainContent.getJSONObject(j).getString("nextHash"); + String rePreviousHash, reNextHash; + if (tokenChainContent.length() > 1) { + if (j == 0) { + rePreviousHash = ""; + String rePrev = calculateHash(new JSONObject().toString(), "SHA3-256"); + reNextHash = calculateHash(tokenChainContent.getJSONObject(j + 1).getString("tid"), + "SHA3-256"); + + if (!((rePreviousHash.equals(previousHash) || rePrev.equals(previousHash)) + && reNextHash.equals(nextHash))) { + chainFlag = false; + } + + } else if (j == tokenChainContent.length() - 1) { + rePreviousHash = calculateHash(tokenChainContent.getJSONObject(j - 1).getString("tid"), + "SHA3-256"); + reNextHash = ""; + + if (!(rePreviousHash.equals(previousHash) && reNextHash.equals(nextHash))) { + chainFlag = false; + } + + } else { + rePreviousHash = calculateHash(tokenChainContent.getJSONObject(j - 1).getString("tid"), + "SHA3-256"); + reNextHash = calculateHash(tokenChainContent.getJSONObject(j + 1).getString("tid"), + "SHA3-256"); + + if (!(rePreviousHash.equals(previousHash) && reNextHash.equals(nextHash))) { + chainFlag = false; + } + } + } + } + } + + if (!chainFlag) { + String errorMessage = "Broken Cheque Chain"; + output.println("423"); + 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(); + } + + boolean ownerCheck = true; + + JSONArray allTokens = new JSONArray(); + for (int i = 0; i < wholeTokens.length(); i++) + allTokens.put(wholeTokens.getString(i)); + for (int i = 0; i < partTokens.length(); i++) + allTokens.put(partTokens.getString(i)); + + JSONArray allTokensChains = new JSONArray(); + for (int i = 0; i < wholeTokenChainContent.size(); i++) + allTokensChains.put(wholeTokenChainContent.get(i)); + for (int i = 0; i < partTokenChainContent.length(); i++) + allTokensChains.put(partTokenChainContent.get(i)); + + JSONArray invalidTokens = new JSONArray(); + + for (int count = 0; count < wholeTokens.length(); count++) { + + String tokens = null; + TokenReceiverLogger.debug("wholeTokens is " + wholeTokens.get(count).toString()); + JSONArray tokenChain = new JSONArray("[" + wholeTokens.get(count).toString() + "]"); + TokenReceiverLogger.debug("tokenChain is " + tokenChain); + String TokenContent = get(wholeTokens.getString(count), ipfs); + TokenReceiverLogger.debug("TokenContent is " + TokenContent); + String tokenLevel = TokenContent.substring(0, TokenContent.length() - 64); + TokenReceiverLogger.debug("tokenLevel is " + tokenLevel); + String tokenNumberHash = TokenContent.substring(TokenContent.length() - 64); + TokenReceiverLogger.debug("tokenNumberHash is " + tokenNumberHash); + + // String tokenLevel = TokenContent.substring(0, 3); + // String tokenNumberHash = TokenContent.substring(3, + // TokenContent.indexOf("\n")); + + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLimitForLevel = tokenLimit[tokenLevelInt]; + int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); + int minumumStakeHeight = tokenLevelValue * 4; + int tokenNumber = 1204401; + + // check TokenHashTable exists + File tokenHashTable = new File(WALLET_DATA_PATH.concat("TokenHashTable").concat(".json")); + if (!tokenHashTable.exists()) { + tokenHashTable.createNewFile(); + JSONObject tokenHashTableJSON = new JSONObject(); + for (int i = 1; i <= 5000000; i++) { + tokenHashTableJSON.put(calculateHash(String.valueOf(i), "SHA-256"), i); + } + writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); + } + String tokenHashTableData = readFile(tokenHashTable.toString()); + JSONObject tokenHashTableJSON = new JSONObject(tokenHashTableData); + if (tokenHashTableJSON.has(tokenNumberHash)) { + tokenNumber = tokenHashTableJSON.getInt(tokenNumberHash); + TokenReceiverLogger.debug("Token Number: " + tokenNumber); + if (tokenNumber > tokenLimitForLevel) { + String errorMessage = "Token Number is greater than Token Limit for the Level"; + output.println("426"); + 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 { + TokenReceiverLogger.debug("Invalid Content Found in Token : " + tokenNumberHash); + String errorMessage = "Invalid Content Found in Token"; + output.println("426"); + 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(); + } + + // ! check quorum signs for previous transaction for the tokenchain to verify + // ! the ownership of sender for the token + + if ((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { + + JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); + TokenReceiverLogger.debug("Last Object = " + lastObject); + + if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { + + TokenReceiverLogger.debug("Checking ownership"); + String owner = lastObject.getString("owner"); + tokens = allTokens.getString(count); + String hashString = tokens.concat(senderDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + String ownerIdentity = hashForPositions.concat(positionsArray.getString(count)); + String ownerRecalculated = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here Sender Calculation"); + TokenReceiverLogger.debug("tokens: " + tokens); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positionsArray.getString(count)); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerRecalculated); + + if (!owner.equals(ownerRecalculated)) { + ownerCheck = false; + invalidTokens.put(tokens); + } + + if (ownerCheck && (tokenChain.length() < minumumStakeHeight)) { + // && (tokenNumber > 1204400) + JSONObject genesiObject = tokenChain.getJSONObject(0); + JSONArray stakeDataArray = genesiObject.getJSONArray(MiningConstants.MINE_ID); + + int randomNumber = new Random().nextInt(15); + JSONObject genesisSignaturesContent = genesiObject + .getJSONObject(MiningConstants.QUORUM_SIGN_CONTENT); + Iterator randomKey = genesisSignaturesContent.keys(); + for (int i = 0; i < randomNumber; i++) { + randomKey.next(); + } + /** + * String randomKeyString = randomKey.next().toString(); JSONObject + * verificationPick = new JSONObject(); verificationPick.put("did", + * randomKeyString); verificationPick.put("hash", + * genesiObject.getString("tid")); verificationPick.put("signature", + * genesisSignaturesContent.getString(randomKeyString)); + * + * if (verificationPick.getString("hash").equals(genesiObject.getString("tid"))) + * { + * + * if (Authenticate.verifySignature(verificationPick.toString())) { + * TokenReceiverLogger.debug("Staking check (3) successful"); } else { + * TokenReceiverLogger.debug( "Staking check (3) failed: Could not verify + * genesis credit signature"); ownerCheck = false; invalidTokens.put(tokens); } + * } else { TokenReceiverLogger.debug( "Staking check (3) failed: Genesis TID is + * not equal to the hash of the genesis signature"); ownerCheck = false; + * invalidTokens.put(tokens); } + */ + // else { + // TokenReceiverLogger.debug("Staking check (3) failed: Genesis Signature not + // found"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + + if (stakeDataArray.length() == 3) { + + JSONObject oneOfThreeStake = stakeDataArray.getJSONObject(0); + JSONObject twoOfThreeStake = stakeDataArray.getJSONObject(1); + JSONObject threeOfThreeStake = stakeDataArray.getJSONObject(2); + + String[] stakedTokenTC = new String[3]; + String[] stakedTokenSignTC = new String[3]; + String[] stakerDIDTC = new String[3]; + String[] mineIDTC = new String[3]; + String[] mineIDSignTC = new String[3]; + + stakedTokenTC[0] = oneOfThreeStake.getString(MiningConstants.STAKED_TOKEN); + stakedTokenSignTC[0] = oneOfThreeStake.getString(MiningConstants.STAKED_TOKEN_SIGN); + stakerDIDTC[0] = oneOfThreeStake.getString(MiningConstants.STAKED_QUORUM_DID); + mineIDTC[0] = oneOfThreeStake.getString(MiningConstants.MINE_ID); + mineIDSignTC[0] = oneOfThreeStake.getString(MiningConstants.MINE_ID_SIGN); + + stakedTokenTC[1] = twoOfThreeStake.getString(MiningConstants.STAKED_TOKEN); + stakedTokenSignTC[1] = twoOfThreeStake.getString(MiningConstants.STAKED_TOKEN_SIGN); + stakerDIDTC[1] = twoOfThreeStake.getString(MiningConstants.STAKED_QUORUM_DID); + mineIDTC[1] = twoOfThreeStake.getString(MiningConstants.MINE_ID); + mineIDSignTC[1] = twoOfThreeStake.getString(MiningConstants.MINE_ID_SIGN); + + stakedTokenTC[2] = threeOfThreeStake.getString(MiningConstants.STAKED_TOKEN); + stakedTokenSignTC[2] = threeOfThreeStake.getString(MiningConstants.STAKED_TOKEN_SIGN); + stakerDIDTC[2] = threeOfThreeStake.getString(MiningConstants.STAKED_QUORUM_DID); + mineIDTC[2] = threeOfThreeStake.getString(MiningConstants.MINE_ID); + mineIDSignTC[2] = threeOfThreeStake.getString(MiningConstants.MINE_ID); + + for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { + + String mineIDContent = get(mineIDTC[stakeCount], ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + TokenReceiverLogger.debug(mineIDContentJSON.toString()); + + JSONObject stakeData = mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); + + String stakerDIDMineData = stakeData.getString(MiningConstants.STAKED_QUORUM_DID); + String stakedTokenMineData = stakeData.getString(MiningConstants.STAKED_TOKEN); + String stakedTokenSignMineData = stakeData + .getString(MiningConstants.STAKED_TOKEN_SIGN); + + TokenReceiverLogger.debug(stakerDIDTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenTC[stakeCount]); + TokenReceiverLogger.debug(stakedTokenSignTC[stakeCount]); + + TokenReceiverLogger.debug(stakerDIDMineData); + TokenReceiverLogger.debug(stakedTokenMineData); + TokenReceiverLogger.debug(stakedTokenSignMineData); + + if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) + && stakedTokenTC[stakeCount].equals(stakedTokenMineData) + && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { + + JSONObject detailsToVerify = new JSONObject(); + detailsToVerify.put("did", stakerDIDTC[stakeCount]); + detailsToVerify.put("hash", mineIDTC[stakeCount]); + detailsToVerify.put("signature", mineIDSignTC[stakeCount]); + if (Authenticate.verifySignature(detailsToVerify.toString())) { + + boolean minedTokenStatus = true; + ArrayList ownersArray = IPFSNetwork + .dhtOwnerCheck(stakedTokenTC[stakeCount]); + for (int i = 0; i < ownersArray.size(); i++) { + if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { + minedTokenStatus = false; + } + } + if (!minedTokenStatus) { + TokenReceiverLogger.debug("Staked token is not found with staker DID: " + + stakerDIDTC[stakeCount]); + ownerCheck = false; + invalidTokens.put(tokens); + } + + } else { + TokenReceiverLogger.debug( + "Staking check (2) failed - unable to verify mine ID signature by staker: " + + stakerDIDTC[stakeCount]); + ownerCheck = false; + invalidTokens.put(tokens); + } + + TokenReceiverLogger.debug("MineID Verification Successful with Staking node: " + + stakerDIDTC[stakeCount]); + } else { + TokenReceiverLogger.debug("Staking check (2) failed"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + TokenReceiverLogger.debug("Staking check (2) successful"); + // } else { + // TokenReceiverLogger.debug( + // "Staking check (2) failed: Could not verify mine ID signature"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + } + + } else { + ownerCheck = false; + TokenReceiverLogger.debug("Staked Token is not available!"); + + } + + } + } + if (lastObject.has(MiningConstants.STAKED_TOKEN)) { + + Boolean minedTokenStatus = true; + + String mineID = lastObject.getString(MiningConstants.MINE_ID); + + String mineIDContent = get(mineID, ipfs); + JSONObject mineIDContentJSON = new JSONObject(mineIDContent); + + JSONObject stakeData = mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); + + ArrayList ownersArray = IPFSNetwork + .dhtOwnerCheck(stakeData.getString(MiningConstants.STAKED_TOKEN)); + for (int i = 0; i < ownersArray.size(); i++) { + if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + stakeData.getString(MiningConstants.STAKED_TOKEN), + mineIDContentJSON.getString("tokenContent"))) { + minedTokenStatus = false; + } + } + if (!minedTokenStatus) { + TokenReceiverLogger.debug("Staking check failed: Found staked token but token height < 46"); + ownerCheck = false; + invalidTokens.put(tokens); + } + + TokenReceiverLogger.debug( + "Staking check failed: Found staked token but unable to transfer while mined token height is not satisfied for the network"); + ownerCheck = false; + invalidTokens.put(tokens); + + // JSONObject tokenToVerify = new JSONObject(); + // if (mineIDContentJSON.has(MiningConstants.STAKE_DATA)) { + + // JSONObject stakeData = + // mineIDContentJSON.getJSONObject(MiningConstants.STAKE_DATA); + // String stakerDID = stakeData.getString(STAKED_QUORUM_DID); + // String stakedToken = stakeData.getString(STAKED_TOKEN); + // String stakedTokenSign = stakeData.getString(STAKED_TOKEN_SIGN); + + // tokenToVerify.put("did", senderDidIpfsHash); + // tokenToVerify.put("hash", stakedToken); + // tokenToVerify.put("signature", stakedTokenSign); + + // if (Authenticate.verifySignature(tokenToVerify.toString())) { + + // ArrayList ownersArray = IPFSNetwork.dhtOwnerCheck(stakedToken); + // for (int i = 0; i < ownersArray.size(); i++) { + // if (!VerifyStakedToken.Contact(ownersArray.get(i), SEND_PORT + 16, + // mineIDContentJSON.getString("tokenContent"))) { + // minedTokenStatus = false; + // } + // } + // if (!minedTokenStatus) { + // TokenReceiverLogger + // .debug("Staking check failed: Found staked token but token height < 46"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to transfer while mined + // token height is not satisfied for the network"); + // ownerCheck = false; + // invalidTokens.put(tokens); + + // } else { + // TokenReceiverLogger.debug( + // "Staking check failed: Found staked token but unable to verify staked token + // height"); + // ownerCheck = false; + // invalidTokens.put(tokens); + // } + // } + + } + } + } + + if (!ownerCheck) { + TokenReceiverLogger.debug("Ownership Check Failed"); + String errorMessage = "Ownership Check Failed"; + output.println("424"); + output.println(invalidTokens.toString()); + 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 + TokenReceiverLogger.debug("Ownership Check Passed"); + + // ------------------------------------------------------- + + boolean partsAvailable = true; + for (int i = 0; i < partTokenChainContent.length(); i++) { + Double senderCount = 0.000D, receiverCount = 0.000D; + JSONArray tokenChainContent = partTokenChainContent.getJSONArray(i); + for (int k = 0; k < tokenChainContent.length(); k++) { + if (tokenChainContent.getJSONObject(k).has("role")) { + if (tokenChainContent.getJSONObject(k).getString("role").equals("Sender") + && tokenChainContent.getJSONObject(k).getString("sender").equals(senderDidIpfsHash)) { + senderCount += tokenChainContent.getJSONObject(k).getDouble("amount"); + } else if (tokenChainContent.getJSONObject(k).getString("role").equals("Receiver") + && tokenChainContent.getJSONObject(k).getString("receiver").equals(senderDidIpfsHash)) { + receiverCount += tokenChainContent.getJSONObject(k).getDouble("amount"); + } + } + } + FunctionsLogger.debug("Sender Parts: " + formatAmount(senderCount)); + FunctionsLogger.debug("Receiver Parts: " + formatAmount(receiverCount)); + Double availableParts = receiverCount - senderCount; + + availableParts = formatAmount(availableParts); + availableParts += amountLedger.getDouble(partTokens.getString(i)); + availableParts = formatAmount(availableParts); + + if (availableParts > 1.000D) { + TokenReceiverLogger.debug("Token wholly spent: " + partTokens.getString(i)); + TokenReceiverLogger.debug("Parts: " + availableParts); + partsAvailable = false; + } + } + if (!partsAvailable) { + String errorMessage = "Token wholly spent already"; + output.println("425"); + 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(); + } + output.println("200"); + + String senderDetails; + try { + senderDetails = input.readLine(); + } catch (SocketException e) { + TokenReceiverLogger.warn("Sender Stream Null - Sender Details"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - Sender Details"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + JSONObject SenderDetails = new JSONObject(senderDetails); + String senderSignature = SenderDetails.getString("sign"); + String tid = SenderDetails.getString("tid"); + String comment = SenderDetails.getString("comment"); + String Status = SenderDetails.getString("status"); + String QuorumDetails = SenderDetails.getString("quorumsign"); + + BufferedImage senderWidImage = ImageIO.read(new File(DATA_PATH + senderDidIpfsHash + "/PublicShare.png")); + SenWalletBin = PropImage.img2bin(senderWidImage); + + 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")) { + quorumSignatures = new JSONObject(QuorumDetails); + String selectQuorumHash = calculateHash(senderToken, "SHA3-256"); + String verifyQuorumHash = calculateHash(selectQuorumHash.concat(receiverDidIpfsHash), "SHA3-256"); + + Iterator keys = quorumSignatures.keys(); + while (keys.hasNext()) { + String key = keys.next(); + quorumDID.add(key); + } + + for (String quorumDidIpfsHash : quorumDID) { + syncDataTable(quorumDidIpfsHash, null); + String quorumWidIpfsHash = getValues(DATA_PATH + "DataTable.json", "walletHash", "didHash", + quorumDidIpfsHash); + + nodeData(quorumDidIpfsHash, quorumWidIpfsHash, ipfs); + } + + for (int i = 0; i < quorumSignatures.length(); i++) { + + JSONObject detailsForVerify = new JSONObject(); + detailsForVerify.put("did", quorumDID.get(i)); + detailsForVerify.put("hash", verifyQuorumHash); + detailsForVerify.put("signature", quorumSignatures.getString(quorumDID.get(i))); + boolean val = Authenticate.verifySignature(detailsForVerify.toString()); + if (val) + quorumSignVerifyCount++; + } + TokenReceiverLogger.debug("Verified Quorum Count " + quorumSignVerifyCount); + yesQuorum = quorumSignVerifyCount >= quorumSignatures.length(); + } + JSONArray wholeTokenChainHash = new JSONArray(); + for (int i = 0; i < intPart; i++) + wholeTokenChainHash.put(wholeTokenChains.getString(i)); + + String hash = calculateHash( + wholeTokens.toString() + wholeTokenChainHash.toString() + partTokens.toString() + + partTokenChainsHash.toString() + receiverDidIpfsHash + senderDidIpfsHash + comment, + "SHA3-256"); + TokenReceiverLogger.debug("Hash to verify Sender: " + hash); + JSONObject detailsForVerify = new JSONObject(); + detailsForVerify.put("did", senderDidIpfsHash); + detailsForVerify.put("hash", hash); + 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); + APIResponse.put("tid", tid); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender / Quorum not verified"); + TokenReceiverLogger.info("Sender / Quorum not verified"); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + + repo(ipfs); + TokenReceiverLogger.debug("Sender and Quorum Verified"); + output.println("200"); + + String pinDetails; + try { + pinDetails = input.readLine(); + } catch (SocketException e) { + TokenReceiverLogger.warn("Sender Stream Null - Pinning Status"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - Pinning Status"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + if (pinDetails.equals("Unpinned")) { + int count = 0; + for (int i = 0; i < intPart; i++) { + FileWriter fileWriter; + fileWriter = new FileWriter(TOKENS_PATH + wholeTokens.getString(i)); + fileWriter.write(wholeTokenContent.get(i)); + fileWriter.close(); + add(TOKENS_PATH + wholeTokens.getString(i), ipfs); + pin(wholeTokens.getString(i), ipfs); + count++; + + } + + for (int i = 0; i < partTokens.length(); i++) { + File tokenFile = new File(PART_TOKEN_PATH + partTokens.getString(i)); + if (!tokenFile.exists()) + tokenFile.createNewFile(); + FileWriter fileWriter; + fileWriter = new FileWriter(PART_TOKEN_PATH + partTokens.getString(i)); + fileWriter.write(partTokenContent.getString(i)); + fileWriter.close(); + String tokenHash = add(PART_TOKEN_PATH + partTokens.getString(i), ipfs); + pin(tokenHash, ipfs); + + } + + if (count == intPart) { + TokenReceiverLogger.debug("Pinned All Tokens"); + output.println("Successfully Pinned"); + + String essentialShare; + try { + essentialShare = input.readLine(); + } catch (SocketException e) { + TokenReceiverLogger.warn("Sender Stream Null - EShare Details"); + APIResponse.put("did", ""); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Sender Stream Null - EShare Details"); + + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + long endTime = System.currentTimeMillis(); + for (int i = 0; i < intPart; i++) { + String tokens = wholeTokens.getString(i); + String hashString = tokens.concat(receiverDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + + BufferedImage pvt = ImageIO + .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(pvt); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + String ownerIdentity = hashForPositions.concat(positions); + String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here"); + TokenReceiverLogger.debug("tokens: " + wholeTokens.getString(i)); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positions); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); + + ArrayList groupTokens = new ArrayList<>(); + for (int k = 0; k < intPart; k++) { + if (!wholeTokens.getString(i).equals(wholeTokens.getString(k))) + groupTokens.add(wholeTokens.getString(k)); + } + + JSONArray arrToken = new JSONArray(); + JSONObject objectToken = new JSONObject(); + objectToken.put("tokenHash", wholeTokens.getString(i)); + arrToken.put(objectToken); + JSONArray arr1 = new JSONArray(wholeTokenChainContent.get(i)); + JSONObject obj2 = new JSONObject(); + obj2.put("senderSign", senderSignature); + obj2.put("sender", senderDidIpfsHash); + obj2.put("group", groupTokens); + obj2.put("comment", comment); + obj2.put("tid", tid); + obj2.put("owner", ownerIdentityHash); + arr1.put(obj2); + writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); + } + + for (int i = 0; i < partTokens.length(); i++) { + JSONObject chequeObject = new JSONObject(); + chequeObject.put("sender", senderDidIpfsHash); + chequeObject.put("receiver", receiverDidIpfsHash); + chequeObject.put("parent-token", partTokens.getString(i)); + chequeObject.put("parent-chain", partTokenChains.getJSONArray(partTokens.getString(i))); + Double partAmount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); + chequeObject.put("amount", partAmount); + chequeObject.put("tid", tid); + + writeToFile(LOGGER_PATH.concat(partTokens.getString(i)), chequeObject.toString(), false); + String chequeHash = IPFSNetwork.add(LOGGER_PATH.concat(partTokens.getString(i)), ipfs); + deleteFile(LOGGER_PATH.concat(partTokens.getString(i))); + + String tokens = partTokens.getString(i); + String hashString = tokens.concat(receiverDidIpfsHash); + String hashForPositions = calculateHash(hashString, "SHA3-256"); + BufferedImage pvt = ImageIO + .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png"))); + String firstPrivate = PropImage.img2bin(pvt); + int[] privateIntegerArray1 = strToIntArray(firstPrivate); + String privateBinary = Functions.intArrayToStr(privateIntegerArray1); + String positions = ""; + for (int j = 0; j < privateIntegerArray1.length; j += 49152) { + positions += privateBinary.charAt(j); + } + + String ownerIdentity = hashForPositions.concat(positions); + String ownerIdentityHash = calculateHash(ownerIdentity, "SHA3-256"); + + TokenReceiverLogger.debug("Ownership Here"); + TokenReceiverLogger.debug("tokens: " + partTokens.getString(i)); + TokenReceiverLogger.debug("hashString: " + hashString); + TokenReceiverLogger.debug("hashForPositions: " + hashForPositions); + TokenReceiverLogger.debug("p1: " + positions); + TokenReceiverLogger.debug("ownerIdentity: " + ownerIdentity); + TokenReceiverLogger.debug("ownerIdentityHash: " + ownerIdentityHash); + + JSONObject newPartObject = new JSONObject(); + newPartObject.put("senderSign", senderSignature); + newPartObject.put("sender", senderDidIpfsHash); + newPartObject.put("receiver", receiverDidIpfsHash); + newPartObject.put("comment", comment); + newPartObject.put("tid", tid); + newPartObject.put("nextHash", ""); + newPartObject.put("owner", ownerIdentityHash); + if (partTokenChainContent.getJSONArray(i).length() == 0) + newPartObject.put("previousHash", ""); + else + newPartObject.put("previousHash", + calculateHash(partTokenChainContent.getJSONArray(i) + .getJSONObject(partTokenChainContent.getJSONArray(i).length() - 1) + .getString("tid"), "SHA3-256")); + + newPartObject.put("amount", partAmount); + newPartObject.put("cheque", chequeHash); + newPartObject.put("role", "Receiver"); + + File chainFile = new File( + PART_TOKEN_CHAIN_PATH.concat(partTokens.getString(i)).concat(".json")); + if (chainFile.exists()) { + + String readChain = readFile(PART_TOKEN_CHAIN_PATH + partTokens.getString(i) + ".json"); + JSONArray readChainArray = new JSONArray(readChain); + readChainArray.put(partTokenChainContent.getJSONArray(i) + .getJSONObject(partTokenChainContent.getJSONArray(i).length() - 1)); + readChainArray.put(newPartObject); + + writeToFile(PART_TOKEN_CHAIN_PATH + partTokens.getString(i) + ".json", + readChainArray.toString(), false); + + } else { + partTokenChainContent.getJSONArray(i).put(newPartObject); + writeToFile(PART_TOKEN_CHAIN_PATH + partTokens.getString(i) + ".json", + partTokenChainContent.getJSONArray(i).toString(), false); + } + } + + JSONObject transactionRecord = new JSONObject(); + transactionRecord.put("role", "Receiver"); + transactionRecord.put("tokens", allTokens); + transactionRecord.put("txn", tid); + transactionRecord.put("quorumList", quorumSignatures.keys()); + transactionRecord.put("senderDID", senderDidIpfsHash); + transactionRecord.put("receiverDID", receiverDidIpfsHash); + transactionRecord.put("Date", getCurrentUtcTime()); + transactionRecord.put("totalTime", (endTime - startTime)); + transactionRecord.put("comment", comment); + transactionRecord.put("essentialShare", essentialShare); + amount = formatAmount(amount); + transactionRecord.put("amount-received", amount); + + JSONArray transactionHistoryEntry = new JSONArray(); + transactionHistoryEntry.put(transactionRecord); + updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", + transactionHistoryEntry.toString()); + + for (int i = 0; i < wholeTokens.length(); i++) { + String bankFile = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bankArray = new JSONArray(bankFile); + JSONObject tokenObject1 = new JSONObject(); + tokenObject1.put("tokenHash", wholeTokens.getString(i)); + bankArray.put(tokenObject1); + Functions.writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); + + } + + String partsFile = readFile(PAYMENTS_PATH.concat("PartsToken.json")); + JSONArray partsReadArray = new JSONArray(partsFile); + + for (int i = 0; i < partTokens.length(); i++) { + boolean writeParts = true; + for (int j = 0; j < partsReadArray.length(); j++) { + if (partsReadArray.getJSONObject(j).getString("tokenHash") + .equals(partTokens.getString(i))) + writeParts = false; + } + if (writeParts) { + JSONObject partObject = new JSONObject(); + partObject.put("tokenHash", partTokens.getString(i)); + partsReadArray.put(partObject); + } + } + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partsReadArray.toString(), false); + + TokenReceiverLogger.info("Transaction ID: " + tid + "Transaction Successful"); + output.println("Send Response"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", tid); + APIResponse.put("status", "Success"); + APIResponse.put("tokens", wholeTokens); + APIResponse.put("comment", comment); + APIResponse.put("message", "Transaction Successful"); + TokenReceiverLogger.info(" Transaction Successful"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + output.println("count mistmatch"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "count mismacth"); + TokenReceiverLogger.info(" Transaction failed"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Failed to unpin"); + TokenReceiverLogger.info(" Transaction failed"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Consensus failed at Sender side"); + TokenReceiverLogger.info(" Transaction failed"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + + } catch ( + + Exception e) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + TokenReceiverLogger.error("Exception Occurred", e); + return APIResponse.toString(); + } finally { + try { + ss.close(); + sk.close(); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + } catch (Exception e) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + TokenReceiverLogger.error("Exception Occurred", e); + } + + } + } } diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 092ca843..8e16437c 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -392,8 +392,61 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception ArrayList alphaPeersList; ArrayList betaPeersList; ArrayList gammaPeersList; + + String senderSign = getSignFromShares(pvt, authSenderByRecHash); + + JSONObject partTokenChainArrays = new JSONObject(); + for (int i = 0; i < partTokens.length(); i++) { + String chainContent = readFile(tokenChainPath.concat(partTokens.getString(i)).concat(".json")); + JSONArray chainArray = new JSONArray(chainContent); + JSONObject newLastObject = new JSONObject(); + if (chainArray.length() == 0) { + newLastObject.put("previousHash", ""); + + } else { + JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); + secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); + newLastObject.put("previousHash", + calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + } + + Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); - JSONArray quorumArray; + newLastObject.put("senderSign", senderSign); + newLastObject.put("sender", senderDidIpfsHash); + newLastObject.put("receiver", receiverDidIpfsHash); + newLastObject.put("comment", comment); + newLastObject.put("tid", tid); + newLastObject.put("nextHash", ""); + newLastObject.put("role", "Sender"); + newLastObject.put("amount", amount); + chainArray.put(newLastObject); + partTokenChainArrays.put(partTokens.getString(i), chainArray); + + } + + JSONObject tokenDetails = new JSONObject(); + tokenDetails.put("whole-tokens", wholeTokens); + tokenDetails.put("whole-tokenChains", wholeTokenChainHash); + tokenDetails.put("hashSender", partTokenChainHash); + tokenDetails.put("part-tokens", partTokens); + tokenDetails.put("part-tokenChains", partTokenChainArrays); + tokenDetails.put("sender", senderDidIpfsHash); + String doubleSpendString = tokenDetails.toString(); + + JSONObject tokenObject = new JSONObject(); + tokenObject.put("tokenDetails", tokenDetails); + tokenObject.put("previousSender", tokenPreviousSender); + tokenObject.put("positions", positionsArray); + tokenObject.put("amount", requestedAmount); + tokenObject.put("amountLedger", amountLedger); + + if(Functions.multiplePinCheck(senderDidIpfsHash, tokenObject, ipfs) == 420) { + APIResponse.put("message", "Multiple Owners Found. Kindly re-initiate transaction"); + return APIResponse; + } + + JSONArray quorumArray = new JSONArray(); switch (type) { case 1: { writeToFile(LOGGER_PATH + "tempbeta", tid.concat(senderDidIpfsHash), false); @@ -425,6 +478,23 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } + + TokenSenderLogger.debug("senderDidIpfsHash is "+senderDidIpfsHash+" receiverDidIpfsHash is "+ receiverDidIpfsHash); + TokenSenderLogger.debug("Quorums list is "+quorumArray.toString()); + if(quorumArray.toString().contains(senderDidIpfsHash)||quorumArray.toString().contains(receiverDidIpfsHash)) { + JSONArray updatedQuourmList = new JSONArray(); + TokenSenderLogger.debug("senderDidIpfsHash is "+senderDidIpfsHash+" receiverDidIpfsHash is "+ receiverDidIpfsHash + " is found in quorumlist"); + for(int i=0;i Date: Thu, 2 Jun 2022 17:06:04 +0530 Subject: [PATCH 162/179] MultiPinCheck & TknAuth --- src/com/rubix/Resources/APIHandler.java | 27 ++++ src/com/rubix/Resources/Functions.java | 144 ++++++++++++++++++ .../rubix/TokenTransfer/TokenReceiver.java | 55 +++---- src/com/rubix/TokenTransfer/TokenSender.java | 39 +++-- 4 files changed, 215 insertions(+), 50 deletions(-) diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 466442dc..28df4bbb 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -758,5 +758,32 @@ public static JSONArray transactionsByDID(String did) throws JSONException { return resultArray; } + + /** + * A call to generate hashtable in node + * + * @return Message if failed or succeeded + * @throws JSONException + * @throws InterruptedException + * @files TokenHashTable.json + */ + public static JSONArray tokenHashTableGeneration() throws JSONException, InterruptedException { + System.out.println("API Handler - generting hash table"); + StringBuilder result = new StringBuilder(); + JSONArray resultArray = new JSONArray(); + JSONObject jsonObject = new JSONObject(); + boolean generationStatus = false; + File tokenHashTable = new File(DATA_PATH.concat("DataHash")); + System.out.println("File path is "+ tokenHashTable.toString()); + generationStatus = Functions.generateMultiLoopWithHashMap(tokenHashTable.toString()); + + if (generationStatus == true && (tokenHashTable.exists() && (tokenHashTable.length() / (1024 * 1024))>0)) { + jsonObject.put("message", "Token Hash Table Generation successful"); + } else { + jsonObject.put("message", "Unable to generate Token Hash Table! Try again after sometime."); + } + resultArray.put(jsonObject); + return resultArray; + } } diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 3d8793ba..4f340de3 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -36,7 +36,9 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; +import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; @@ -1980,5 +1982,147 @@ public static int multiplePinCheck(String senderDidIpfsHash,JSONObject tokenObje return statusCode; } + + public static boolean generateMultiLoopWithHashMap(String path) throws InterruptedException { + FunctionsLogger.debug("path is " + path); + FunctionsLogger.debug("path with file" + path+"/DH00.json"); + File dataHashPath = new File(path); + if (!dataHashPath.exists()) + dataHashPath.mkdir(); + boolean status = false; + FunctionsLogger.debug("Main thread started at" + java.time.LocalTime.now()); + + long tStart = System.currentTimeMillis(); + Thread generateHashMapThread1 = new Thread(() -> { + FunctionsLogger.debug("T1 started at" + java.time.LocalTime.now()); + HashMap tokenHashMap = new HashMap(); + JSONObject tokenHashTableJSON = new JSONObject(tokenHashMap); + + File tokenHashTable = new File(path+"/DH00.json"); + long start = System.currentTimeMillis(); + for (int i = 1; i <= 1250000; i++) { + tokenHashMap.put(calculateHash(String.valueOf(i), "SHA-256"), i); + } + tokenHashTableJSON = new JSONObject(tokenHashMap); + writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); + FunctionsLogger.debug("T1 ended at" + java.time.LocalTime.now()); + + tokenHashMap.clear(); + long end = System.currentTimeMillis(); + FunctionsLogger.debug("Write to file done in t1 : " + + (end - start) + "ms"); + }); + Thread generateHashMapThread2 = new Thread(() -> { + System.out.println("T2 started at" + java.time.LocalTime.now()); + + HashMap tokenHashMap = new HashMap(); + JSONObject tokenHashTableJSON = new JSONObject(tokenHashMap); + long start = System.currentTimeMillis(); + File tokenHashTable = new File(path+"/DH01.json"); + + for (int i = 1250001; i < 2500000; i++) { + tokenHashMap.put(calculateHash(String.valueOf(i), "SHA-256"), i); + } + tokenHashTableJSON = new JSONObject(tokenHashMap); + writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); + FunctionsLogger.debug("T2 ended at" + java.time.LocalTime.now()); + + tokenHashMap.clear(); + long end = System.currentTimeMillis(); + FunctionsLogger.debug("Write to file done in t2 : " + + (end - start) + "ms"); + }); + + Thread generateHashMapThread3 = new Thread(() -> { + System.out.println("T3 started at" + java.time.LocalTime.now()); + + HashMap tokenHashMap = new HashMap(); + JSONObject tokenHashTableJSON = new JSONObject(tokenHashMap); + long start = System.currentTimeMillis(); + File tokenHashTable = new File(path+"/DH02.json"); + for (int i = 2500001; i <= 3750000; i++) { + tokenHashMap.put(calculateHash(String.valueOf(i), "SHA-256"), i); + } + tokenHashTableJSON = new JSONObject(tokenHashMap); + writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); + FunctionsLogger.debug("T3 ended at" + java.time.LocalTime.now()); + + tokenHashMap.clear(); + + long tEnd = System.currentTimeMillis(); + System.out.println("Write to file done in t3 : " + + (tEnd - start) + "ms"); + }); + + Thread generateHashMapThread4 = new Thread(() -> { + System.out.println("T4 started at" + java.time.LocalTime.now()); + + HashMap tokenHashMap = new HashMap(); + JSONObject tokenHashTableJSON = new JSONObject(tokenHashMap); + long start = System.currentTimeMillis(); + File tokenHashTable = new File(path+"/DH03.json"); + for (int i = 3750001; i <= 5000000; i++) { + tokenHashMap.put(calculateHash(String.valueOf(i), "SHA-256"), i); + } + tokenHashTableJSON = new JSONObject(tokenHashMap); + writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); + FunctionsLogger.debug("T4 ended at" + java.time.LocalTime.now()); + + tokenHashMap.clear(); + long end = System.currentTimeMillis(); + FunctionsLogger.debug("Write to file done in t4 : " + + (end - start) + "ms"); + }); + + generateHashMapThread1.start(); + generateHashMapThread2.start(); + generateHashMapThread3.start(); + generateHashMapThread4.start(); + + + + FunctionsLogger.debug("Main ended at" + java.time.LocalTime.now()); + + long end = System.currentTimeMillis(); + FunctionsLogger.debug("Main thread" + + (end - tStart) + "ms"); + + generateHashMapThread1.join(); + generateHashMapThread2.join(); + generateHashMapThread3.join(); + generateHashMapThread4.join(); + + File filepath = new File(path); + if ((filepath.length() == 4)) { + FunctionsLogger.debug("DataHashTable size is"+filepath.length()); + status = true; + }else{ + status = false; + } + + return status; + } + + public static int readTokenHashTable(String path,String tokenContent) throws JSONException { + File filePath = new File(path); + FunctionsLogger.debug("File path to add is "+path); + File[] tokenHashTable = filePath.listFiles(); + Arrays.sort(tokenHashTable); + int tokenNumber = -1; + + for (File tokenHashTableFile : tokenHashTable) { + FunctionsLogger.debug(tokenHashTableFile.getName()); + JSONObject tokenHashTableJSON = new JSONObject(readFile(tokenHashTableFile.toString())); + if (tokenHashTableJSON.has(tokenContent)) { + tokenNumber = tokenHashTableJSON.getInt(tokenContent); + return tokenNumber; + } + + } + return tokenNumber; + + } + + } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 38e21588..c535f5bb 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -380,7 +380,6 @@ public static String receive() { JSONArray invalidTokens = new JSONArray(); for (int count = 0; count < wholeTokens.length(); count++) { - String tokens = null; TokenReceiverLogger.debug("wholeTokens is " + wholeTokens.get(count).toString()); JSONArray tokenChain = new JSONArray("[" + wholeTokens.get(count).toString() + "]"); @@ -400,23 +399,34 @@ public static String receive() { int tokenLimitForLevel = tokenLimit[tokenLevelInt]; int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); int minumumStakeHeight = tokenLevelValue * 4; - int tokenNumber = 1204401; + int tokenNumber = -1; // check TokenHashTable exists - File tokenHashTable = new File(WALLET_DATA_PATH.concat("TokenHashTable").concat(".json")); + File tokenHashTable = new File(DATA_PATH.concat("DataHash")); if (!tokenHashTable.exists()) { - tokenHashTable.createNewFile(); - JSONObject tokenHashTableJSON = new JSONObject(); - for (int i = 1; i <= 5000000; i++) { - tokenHashTableJSON.put(calculateHash(String.valueOf(i), "SHA-256"), i); + if(generateMultiLoopWithHashMap(tokenHashTable.toString())) { + TokenReceiverLogger.debug("Initating check"); } - writeToFile(tokenHashTable.toString(), tokenHashTableJSON.toString(), false); } - String tokenHashTableData = readFile(tokenHashTable.toString()); - JSONObject tokenHashTableJSON = new JSONObject(tokenHashTableData); - if (tokenHashTableJSON.has(tokenNumberHash)) { - tokenNumber = tokenHashTableJSON.getInt(tokenNumberHash); - TokenReceiverLogger.debug("Token Number: " + tokenNumber); + tokenNumber = Functions.readTokenHashTable(tokenHashTable.toString(),tokenNumberHash); + if(tokenNumber == -1) { + + TokenReceiverLogger.debug("Invalid Content Found in Token : " + tokenNumberHash); + String errorMessage = "Invalid Content Found in Token"; + output.println("426"); + 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(); + + } if (tokenNumber > tokenLimitForLevel) { String errorMessage = "Token Number is greater than Token Limit for the Level"; output.println("426"); @@ -432,27 +442,12 @@ public static String receive() { ss.close(); return APIResponse.toString(); } - } else { - TokenReceiverLogger.debug("Invalid Content Found in Token : " + tokenNumberHash); - String errorMessage = "Invalid Content Found in Token"; - output.println("426"); - 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(); - } + // ! check quorum signs for previous transaction for the tokenchain to verify // ! the ownership of sender for the token - if ((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { + if((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); TokenReceiverLogger.debug("Last Object = " + lastObject); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 8e16437c..7b1ded1d 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -444,9 +444,11 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception if(Functions.multiplePinCheck(senderDidIpfsHash, tokenObject, ipfs) == 420) { APIResponse.put("message", "Multiple Owners Found. Kindly re-initiate transaction"); return APIResponse; + }else { + TokenSenderLogger.debug("No Multiple Pins found, initating transcation"); } - JSONArray quorumArray = new JSONArray(); + JSONArray quorumArrayList = new JSONArray(); switch (type) { case 1: { writeToFile(LOGGER_PATH + "tempbeta", tid.concat(senderDidIpfsHash), false); @@ -457,17 +459,17 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); deleteFile(LOGGER_PATH + "tempgamma"); - quorumArray = getQuorum(senderDidIpfsHash, receiverDidIpfsHash, + quorumArrayList = getQuorum(senderDidIpfsHash, receiverDidIpfsHash, allTokens.length()); break; } case 2: { - quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + quorumArrayList = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); break; } case 3: { - quorumArray = detailsObject.getJSONArray("quorum"); + quorumArrayList = detailsObject.getJSONArray("quorum"); break; } default: { @@ -479,23 +481,20 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } - TokenSenderLogger.debug("senderDidIpfsHash is "+senderDidIpfsHash+" receiverDidIpfsHash is "+ receiverDidIpfsHash); - TokenSenderLogger.debug("Quorums list is "+quorumArray.toString()); - if(quorumArray.toString().contains(senderDidIpfsHash)||quorumArray.toString().contains(receiverDidIpfsHash)) { - JSONArray updatedQuourmList = new JSONArray(); - TokenSenderLogger.debug("senderDidIpfsHash is "+senderDidIpfsHash+" receiverDidIpfsHash is "+ receiverDidIpfsHash + " is found in quorumlist"); - for(int i=0;i quorumList = new ArrayList(); + for (int i = 0; i < quorumArrayList.length(); i++) { + if (!(quorumArrayList.get(i).equals(senderDidIpfsHash)) && !(quorumArrayList.get(i).equals(receiverDidIpfsHash))) { + quorumList.add(quorumArrayList.get(i).toString()); + } } - TokenSenderLogger.debug("Final quorums list is "+quorumArray.toString()); - - + for (int i = 0; i < quorumList.size(); i++) { + quorumArray.put(quorumList.get(i)); + } + + + TokenSenderLogger.debug("Updated quorumlist is "+quorumArray.toString()); + int alphaCheck = 0, betaCheck = 0, gammaCheck = 0; JSONArray sanityFailedQuorum = new JSONArray(); for (int i = 0; i < quorumArray.length(); i++) { From 7f9453fa69f49f2c724d597cac7bde8ca6097f7b Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Thu, 2 Jun 2022 19:33:02 +0530 Subject: [PATCH 163/179] Implemented SAnity Check in Mining, --- src/com/rubix/Mining/ProofCredits.java | 32 +++++++++++++ src/com/rubix/Resources/APIHandler.java | 48 ++++++++++++++++++++ src/com/rubix/TokenTransfer/TokenSender.java | 5 ++ 3 files changed, 85 insertions(+) diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 0edf488c..1f013629 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -14,9 +14,12 @@ 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.getValues; 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.sanityCheck; +import static com.rubix.Resources.Functions.sanityMessage; import static com.rubix.Resources.Functions.strToIntArray; import static com.rubix.Resources.Functions.updateJSON; import static com.rubix.Resources.Functions.updateQuorum; @@ -245,7 +248,36 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON ProofCreditsLogger.debug("Final quorums list is "+quorumArray.toString()); + // Sanity Check - Start + int alphaCheck = 0, betaCheck = 0, gammaCheck = 0; + JSONArray sanityFailedQuorum = new JSONArray(); + for (int i = 0; i < quorumArray.length(); i++) { + String quorumPeerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", + quorumArray.getString(i)); + boolean quorumSanityCheck = sanityCheck("Quorum", quorumPeerID, ipfs, SEND_PORT + 11); + + if (!quorumSanityCheck) { + sanityFailedQuorum.put(quorumPeerID); + if (i <= 6) + alphaCheck++; + if (i >= 7 && i <= 13) + betaCheck++; + if (i >= 14 && i <= 20) + gammaCheck++; + } + } + if (alphaCheck > 2 || betaCheck > 2 || gammaCheck > 2) { + APIResponse.put("did", DID); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + String message = "Quorum: ".concat(sanityFailedQuorum.toString()).concat(" "); + APIResponse.put("message", message.concat(sanityMessage)); + ProofCreditsLogger.warn("Quorum: ".concat(message.concat(sanityMessage))); + return APIResponse; + } + //Sanity Check - Ends + QuorumSwarmConnect(quorumArray, ipfs); alphaSize = quorumArray.length() - 14; diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 28df4bbb..c2fdf08b 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -785,5 +785,53 @@ public static JSONArray tokenHashTableGeneration() throws JSONException, Interru resultArray.put(jsonObject); return resultArray; } + + /** + * This method is to get the no. of staked tokens + * + * @param + * @return no. of staked token + * @throws JSONException handles JSON Exceptions + * @files + */ + public static int stakedTokencount() throws JSONException { + String stakedtokens = Functions.WALLET_DATA_PATH.concat("Stake/"); + int count =0; + File stkedtokensfile = new File(stakedtokens); + File[] filesList = stkedtokensfile.listFiles(); + if (stkedtokensfile.exists()) { + for ( File file : filesList) { + String sFile = file.getName(); + String k = stakedtokens+sFile; + String contactsFile = Functions.readFile(k); + + JSONObject js = new JSONObject(contactsFile); + + JSONObject stakedata = js.getJSONObject("stakeData"); + String staked_mineid = stakedata.getString("stakedToken"); + count++; + } + } + return count; + } + + /** + * This method is to get the withdrawal balance + * + * @param + * @return withdrawal balance + * @throws JSONException handles JSON Exceptions + * @files + */ + public static Double getAvailableBalance() throws JSONException, IOException + { + int stakedtokens=APIHandler.stakedTokencount(); + Double balance=Functions.getBalance(); + + Double availablebalance = balance - stakedtokens; + + return availablebalance; + + } } diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 7b1ded1d..ff31990d 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -895,6 +895,11 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } TokenSenderLogger.debug("Operation over"); + + for (int i = 0; i < wholeTokens.length(); i++) + unpin(String.valueOf(wholeTokens.get(i)), ipfs); + repo(ipfs); + Iterator keys = InitiatorConsensus.quorumSignature.keys(); JSONArray signedQuorumList = new JSONArray(); while (keys.hasNext()) From d35a7b22263d3b7a7c3337c587ed8e40a87e5a34 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Mon, 13 Jun 2022 15:06:40 +0530 Subject: [PATCH 164/179] Included Methods to check SHA256 and check token Authenticity --- .../rubix/AuthenticateNode/Authenticate.class | Bin 3140 -> 1040 bytes .../rubix/AuthenticateNode/SecretShare.class | Bin 23619 -> 15740 bytes .../rubix/AuthenticateNode/SplitShares.class | Bin 2940 -> 1013 bytes .../rubix/Consensus/InitiatorConsensus.class | Bin 7266 -> 4195 bytes .../rubix/Consensus/InitiatorProcedure.class | Bin 4211 -> 1645 bytes .../com/rubix/Consensus/QuorumConsensus.class | Bin 4680 -> 5416 bytes .../rubix/Constants/ConsensusConstants.class | Bin 515 -> 592 bytes .../com/rubix/Constants/IPFSConstants.class | Bin 1193 -> 1149 bytes .../RubiX/com/rubix/Resources/Functions.class | Bin 13126 -> 14229 bytes .../com/rubix/Resources/IPFSNetwork.class | Bin 7152 -> 4776 bytes .../com/rubix/SplitandStore/Recombine.class | Bin 2390 -> 917 bytes .../rubix/SplitandStore/SeperateShares.class | Bin 824 -> 822 bytes .../RubiX/com/rubix/SplitandStore/Split.class | Bin 3173 -> 1008 bytes src/com/rubix/Resources/Functions.java | 94 +++++++++++++++++- src/com/rubix/TokenTransfer/TokenSender.java | 40 ++++---- 15 files changed, 115 insertions(+), 19 deletions(-) diff --git a/out/production/RubiX/com/rubix/AuthenticateNode/Authenticate.class b/out/production/RubiX/com/rubix/AuthenticateNode/Authenticate.class index 27d1a54271859879c7cdd78193031de16ebbeb20..d2760882a6d82ba4a5805baf8c473a9729a3408b 100644 GIT binary patch literal 1040 zcmb_bU2oGc6g@7bX|qDRj*V~d_z)XH&C8zHgoLIc4TTn|-6VK(GcR?O+L7Z_+b=@` z3Eufph}#slPAX_fyx7;i$H&*_Tz~)Z`73}OJoQjwcovy)VDo`G30~)JD790OaI#~L zWGL^_RUWP}G|t)gtTncZ24l?wZDnSXi9F&|YN`_9l+ir3W{}8n_LBRx{!nr? zPK|Zk*tjiH5e;QKG4a-jM?!1k_(1aCH2;pDJ!SzFcZLh@PE+aE{s{7G@2yFtbtHm5 zR&j2HGj;*nUpVG2@=?cf9W}HVRyV?P&3eu%9dA!HZG=k8PCgz;+ZQAg*%X>cB!|MP z>H61Z*$q|3uo+&m2guIG%+8*QwQ#v5=7lwUWbpS+BAHIT$~@dDZQD$`Tw%6^P<*IndkY2+5|Eez4-7~q3@bRb$}iDsi%^Va{|o9LTGv0J`K`dL&{!!lE!?2E vK0{#@YqYB2CTluz>AF!B(PkCGcWg#}k^%#Q*3g7(25&oV?YDsGOE3V|Nf1=t>Ldurd)GeD(wrfkW8aj-mM6%RaP1+^7lGa|4 z^l~X%sq3b#n&i-9QJ_8Q5}@#*Kd2HUh0&f06zD0J9*iDZpg^xZ6h?qX{oYa%DN!ie z2-@9w^XAQbGxN>kA3y!@5r7=t3F8=wVZ`uq7}J=MuUQ4Jgb`?|UzO6Fg848)QWL-p zDJ_Jth_6fOH3c{2`6apc4Jo}I!W;Nz5Z?;JKq-i_f{FrDp!cFxwcN`BzI0|mz&}x| zP#Y^+Rdc$zRx+J=qhwQ)EY`|~y!xEZZ_HUMRl{vM^!!q~c*|HfvbIrO$Zt5Y>+b}ynpsL{?#UACNtJL_2MEQLU%VU}yv%Klnq?VR>9(S=)}XNi~x zyEeRpSoUbctX52CaUYQ01$ew^*)(C@2aS%#Oqwoh(kNODS3ql>YPy!4z3Mo|hE(%J z+#%q#5{XcG)oe6vnx?w2OnQYnsJ>}BHQFAk=lF(e5_HcJYpxyMv#N%((XDT>flWPR z&!S77apNE>H|l%L%p8@}#jg5{U1p+@IoBxPe%YvdtX6PA!6kw4wR>f=?lDQhvVs)_ z3>coPHJ!3KWyzUHbdr5kl0}7%&#AC*OTldwHr7;B!D`=vb@IZR{u8Oy$`S(0ao7)FoGINh%Vbb1N2``C%(EH%74gI>~w!fxL??-GHNZNy}<*T6=0s#z_2 z-R0;zMzvB~n{ChW;1PFHAtT2zx=gOx9i~cpiDBhdZ+X>lt};n~x{#UR+Njq#p#mq; z6WzGlqZxE-dqhvAyA8=upHZP3trJwMpkwmNd#0UUXQ#c}cdl+*?i_K+*$eGYw7~gY zX9wvvcI4bh1S_VzDwtTu4DDjzrO4gg`SzzXa>7p>v~1C>ZI{T!!_3! zs@9aDT5-q}-k4RF4oqW>K=ujLp%zf;(#YnuexOLLuw$78d>(`RQI&r^5OPTQKF(E^ zU%_u+_C?w*Z z92lXHIOfT{=i@^kz?WBaMGF3W@FN6Xdmp{|kRHs3_3)!ypD(9ss@AuK6M9%vM{^N9 zbWV$GL)k`faZ?rV?fmT{gm@?{59pz7^ld|3r0C!M26n%_t?vhj__h)K9b);u-S}#J z=(pi~#FvX|(fH672K0y))m1Gz8oy%CY(^R6AH&;-=c9Z0VtO=}*YC@vw3ODrg_C+xOO56{;S@nC%mkaKSktM=uf7$ zq4^(5X@HXNA^YQp?B7rDG~dS&=4yalJk72Rvu_u078mgh7Vs=e{H{`a2j_7gBiO_! zendk27|&sgmOsar@e6zfAL4oZf!{x23?JhX9^(rBg{$}kwHB8Ksz zcn$@TM^UU`M!1+2_wkB&fE(g%MwNW}CyBT~R-MKfMDS};@hqh%{!L6zQ_|>pnApxB z#WXnr49VrZeDvvk z0LEgm4-p;=t!-&4Y3p3pu)1VYXGeXwxuc;r)DfQ5QWq|%3fH!UJF4nKZDAk09t2i~ z&I*+@hMHHDR4!W?uI=z3qGFN2z(HZ2Rc%?&MU4117V(NY^~oF8gyF#24K9?Prn z=9TBqk3%H#{TPZq#^8m1_z_Q~b<{V|eDW&(yG0vA({J`5aYeW}+(wH!C)8Zm(nM)! zgmNEB#fo-zG&Ghl7>AL_H(o~jQ3hHbUvqeMM|m?Xb#!C6c|}LP2MHqIq_(!uIkbX# zwEpG!HRW+s>KH#tjJU{9TN{nk-f%8W*t628J>1kvO;Qu8IzqLpW`mPTSvRW=lgLoCL7TU{RkR+>oX?R6rvI1s#-eRYQxhSj13N0?%ZPIrbR9VMbd2_ zM|TX}QPhex?kDp~cawRgd&#^~UFMaxoUSp(on>C>zA~?LSD9C;fUZ7rB%=@I?+cV= zQlI`S{W^%B_9CS^G7z&Tt~%iJR#sJeSv%TjN69va(WVe%FrR306w}i;V*}D#9Uy_b z0xZlNDZoOgEnuvf!xUJKIGZ4B@lrJ_3HYsjVM?%zEMKB2vUZYai-wDkrs%sVo901#M&385q6O|N7_VIU8z$O8IDr{%Q8v}MA&E>Wh-0e z)P(tX6|gZ*&;k*5qC#md0-mIYEbkasD8k2@4zGE)juUMG$M*;<-vpZ=Y!ju*)_9V& zFH9%fMV4=}A`1HyN!XfBwf2Q+nq6c$rz@hcpJF4d)^evN%%`e=<)5JiBCJAE=ALQo z3)3vS$efjmDD0=%2&;RxQ!~F&=p$#27Kl_;Hp-TEu2U1{c`Be%1)Z-@R@nlbE`k>7 zAzOiJS17_4NeBCUt+DonX|Y{oxtA!Su%B)tYz}8QHDO+=0?U$wY?Q6;GN&dss#Xic zKy?abm4$V>2wJX(Yz0=hLJ?kXbFioerzXrRRlp)vX@Ll9R4AKQlTH^w&3eejYjK4l zyj5|qtvOSti=Z|=WMj6wLJ{7fb+Ea1x-k)amb-zCe|E11k!H2&iZnml&k=0_&+QRd z&hu=7u$?beR{I6kzA#;A7g@fG6p`D5xL6`{BZ9cZDoER6wK?}paU}N{d&sR;sIAG6Ku3uc-(_dQQ99; z36I&NB{J|~1@rkmq60E)v!3!Xx42T7;8DfGcWSE+$gpjC%Ex`omC6L$wH7|-$K9X| z?{atW8oGOR$V5*_oB0?1AfB`e(ze5{@-cSWR9^fprzn#=r4pX#X)Td~yKR_n&>p8K z?R!jJn~i@r zz3mjG{jVzF_G5;7VnJ4;2gF-;Z=ahW$-X`M4juQkmcr zt%c9|Q#UBXKXZ5R8b0sUArpO}*eG7oLwd@G_`55W3BJ@?_%y$AgEIVUcL%TGn_e9< z(YIO~-|Fw&pbS6k?%;KN->X9=`oY!4*W@3)8DyFtdv_T%b)#P(VE%^Rw1WT7Y60H);ljM+0XE)M<9>|9p@_B~2%TeZv8IL2Xs-tC_FR0HH%pHgkO^zJT zGUzu?(ro^vS=d;dIaDCl%t37d<9Yc1tKiRr0g!t6>R|r_6RK3Ae$g;gQd!99AfPY(@?v}@(oi&Vb7CxB@L}4FpBdpdUrzXtBDq#6bv_OQ7kd(PcTKmFOY8RRFI7JlpQ8vQr9_`eG zxl9Et|M6NN!cMSJw&o`~HDNwU1#FBlS|Gy4DwNG-oK6=(&-HbK~?NR`z))!G-PX?Bt2o34n$eu^Y)t;?-_VLH_=vYay%QP?YNgw;CJ zsR{Ee6|nr3S|Gwsla#qN^$1XBwl_CoJTpM9^&vRvu7_;AGhCqvUn(8!GdyJN3)3>Y$a2>zqOjN52%AIL zsR{FP6|np(v_OQ_+bG+Q2B#*>D^EB#3oZLE5ggtL72}ah0OVfU9kY*L;mrl=k&1;bUB@B{J|j ziMjuJs~~MR*j4VmQBh^UO*X{qzu75D`zr-Vh|lFgrzq_Ysf3TQ zNlRql!#2$K=MkqU?VDA?$JwGKGVoCa^EqwR0U5SUPx+XSxl);6yUoJm9(Rh;-lY;A z)2$^k@CgO;`8}xvGHi#Q@-cV1Qkh_vV&QxEln%(Sr}dPNyW5q@1beg=KIgq|P=@bw zckmjX>D3_3VJXBDLF&vuoMv0qVT!1Ff5=kfaGysafN@UIHy z^Ls}JWZ1iU%Ex@qmC6L~D;B#LM42>Ls}vO|E^#@*DrNIhJB@{e9W(1sZ8*VV&VJytq#br@AQ<9 zd)SrA1m9~de9k|(K^guJcL%TG$6g&W(NBtv$Ny6YWZ2Jo%42_Vr82?4v=%=9|8avd z{D0jYyoO(Ub;v~j*4p?z@S7Wy;lH~(cpZQA>X3WFp@qnh97O9$wvpzTRnu!gQVKAY&lu@QmpB|=e`N1&S1Zt*kWYIIB zZuB>JH*(lz;Nx`GB?5zi$P65yb~J|30hl>-B<3hqIaR_}Q(~%On2>l{AAT{y>q*X z#w0Ak*n}+@m+%e7Cl+8rVml@#zJN(dL7bel5R;R(VoK66ObyJ%w7@n@4;;ZM!LcY0 zUV>AD`!ORq1r^DwFf(~OW+fj*WuGdX)@K`L_w`^--_ual_kPUn`wQl!Ou+n^mHssC6{dpVlK;CcIm_G&&=3kA6@(*ECK`|aKScgXnzQg9iA=py5 z6pt2e!`8x|uxJT`niwhw;?j~5l7tLS2M7rlumiVN{%@g>+%{5p1)^uw-_20T@= zA5V|S!R`^Q*fZiF_KwWMzL9J3%*ZeBZ0SrqS2_=Mr39;ua$m_lE>HwxriiB6RnC)M777jMxU z>1{K-A2VY(ii|w;<|?MsX&$=LX+NH_j65D<{@oZ^y%Wb}?7*l;sc*hP>8)w7cg<{m z=EL#)q#K>T<2ml2QKQH=D05HTtb%>Ja8j8!a@-~)6=fBqcuTX2E7wGLvNAUu`?+X4 z*&>biJ~GUMb01UaCzSA0I(GRP(&?IuL*{U!SV}r`Y83+rPF`B&Y#E-Lxw5Yd*V*=MwUfImPK#Eh{!VECZwiB z6{h$~Q=*FtQhderOUt6x_&h1TtPRJ$P4}imr$kkfe@(O}B|3YZ& zMap8_Bb70MEXuQ-f9Y+`MQUY`>*tg->mswG*_#^CpYF6ckDt~)5jmb@6nXk$l&2rYcv3N&uC?@a o*5b)9r_0`zt^8eCM0aPkIbGw{jYY%}jG;Zurb#X$Ap$l32OeJRWdHyG literal 23619 zcma)^d3;pW701uZOfp#pmAB~G+&A~V%RPV0Tkd@4dw=)5J1;XY?=w$* z^T0L$sDVts54?r=Xu$`zdR^GKVn19crYP0g z*_={)O={7wFE-6=X>Z9L>_K!w-Nfa%n%l7^+>uVT zE>C4!)P7%MG}qjMJxo}f?r5vYcCT((Uo*Qq*PLn3wWL$I%u;mKG-T4*Os=6hmCek+ zK*A?$%sOXX}O~sa&=toxzZ06IRwK7t6{{Y{_=z z=-Kri#Je)-j`lS>cMH<0Jn1PO#5%JbYr4}p)o*uOR}6-tDBYY%pES3l4fPbTZY4XT zX&evcL=p$nl}lxF*l%Qls%uPTML)h^X1cYn=A{iC-Pv?zL5nJI!dIy3b*Yn6aTo*h z;xG~_@k!NC)17N+t>L1@;aJ!w4wKYk1XRXh7z~X=HPpo65I8gryQ|$jU{oA-Q(L3e z)}CrHTOSyB^g_Ws zxKjY*a5)g)S^zIV6kbH>OE4byc4HVOz(m|rp{lS`57$_>K4mR39zGX;5F$O;uq(3O@jc zH3hc{@Rg%rDn26k`rTm~wnbrobe2KEH!#49!C-GNjunqJ=k!J+P>jI5ky}d-ibiT< zk=nwF!jYR`YNWQPqNs8c46leyswkRLQCMA7QB>W$sy4Q<2y=fhELu@m5v#|SY%Ik6 z?ZcvaAXRwS0Y1dIAEEtYNWv#L$v(vze}a)egX!=&%)s{9@Ffjw8B#;AifRz51oMzk zhgxkNh=Wx}V;&qtLsVNca4UlLLtrLyQ5@cZYQ|$rF}BRYtr!h^4n%k0lf^jh7#!@; z_?2u2a(Rs&HdgL{LHVuJZ;5*IaJAqu>`Tq5`r=uYJy38HER4*G^g^r$VpZEVL1kqX zZdFfGi{@3ca1~vJ&u-rFUS(k?z2dqZPxU}?qIe6GEUKEc1xgof-m#@h7p@x90{k71 zh06n17$Hx)eG?+7(fAgVc^cJy)dXpJ&}m1XOfF2 zZQEMf3*~)7?}33h_^~}ujw7bQV~eW6s>05CU4&PAl%*U8jXL!%UrR}2+i zDU9|8z+`U_O!Ja3$18^wxK4XRpu-zV!{v8yXWu(`GLB_F4VMR5@HI@wqg{muc)`v= zHg2JF1~i_Xgg-w7gPS6W;;p4kkw|@06d#57D8fe!AI11csGUSCTHnwVb%0R?Mi4BN zfXY~82bGMwRz|F}Eu#jN5ogmb!TyX1SKmY`r8>-EP6T`fQYjOb-t$RvmN=X`XQ_lF zXPKQ;I$g~~Ttbo)C%&RHQL$+=rNi7Io}4V94O+}%OyoWmp}IfvUxqn;xqBsnV`q|P}~LXvZjd=eEQ zr#U+Aqa-9bM>|NJb599L&b{oUQO_|FlAL25q|Ujwge2#YNiL zBsr_>q*2dF5|W(zI7ppyvV?xi7Io})k;Wm9^fE#&gl}8oCn%TT~8tpa*(?B84{A5Gc}1Xw|u0dbKNWnNzQ{E zq|SMWge2#oc2ZY~a?X~J>zc{Z%asWu4fWox{FJ7bY9vZA<21) zgVZ^{BO%H8T{~&i^LrAKoZoklI_IepQaO`wS~!X>V}d5(2NIO6r#sO8s7d&t1ZC?+ zJDOkAB%C2Z*?Oh}^<_Ovg0l7OAc~@p6KN98k)Uin*Ma)7o+m-sdcGYs>w19%W$T3w zl(I5zxkNm-Q|Q%GSH>s9D#0Bq&>Z9H=jAuLNc5FEomRU0mc#!Y?H#TkmzCzO47z zQL|WEBq#^C-+}r9JRm{Y`d~PUvcM$VDnZ%$kOTE)-6lcV`mi0i3;`iul+>$48jm-RUb%GT%eQIuFe6TTop+4`ab^<{lYg0l5x zJ8IVT6$#4LR~@J?>uVB}t*?ipC=1NjHzX)q-*lk9tbdT8Y<8ZLD~AD1NCM7NP@EU<8TyZfl2s@1ZC@| z4%C7+URp|@!T2Y0k zPP{QM(5l#2e=BnR-r_*3ViQ`S;GN<`zC$$=%@W-8UD!lP3Az2vM3?3@_q)pi%|yrh zo005~ofr^kCVF6AbH95~pc(02C`)=EzKK#*Hp&MR4~%c5VekDy2Z+h|Zp$JGsD>7^ zgG#3UX0owZ0#dPd(KjjkL)vbl#6Hb`=vjJ4mGOp8l!WKZCn;yCgVZ_8BqTZGc2end zITHgUBsm8a@mODtDbFhRY=MXz-)U!fDl5;l)sdEmM zkmTGwoJ5s5KZi+3at?QpI_C%pNzO_;Y1DJ1ge2!44pQeFB_YWbbXsBsdJ8(kmQ^YPNK@3pA#h{IjbC`&N)d!l5-zBY1DJF zgd}IRgVZ@|BqTZa4U(t{JAdvcA;~$#LF$}SB_uhg*-4|G`%6f2);dU?^8g7+>PK zs?7O$poApnK@L*qoFO5}Inz!W^_(Rk$$7AY)Hx54kmNj6llbyoTnA3fmXPF};~;g; zxe}6`^X#Ni&-oIPoC_SJ&bd%RlJl@|5>@8>tdo%BJlsL*oQotRITzbWqn=A7BsrHl zNS(7@LXz`{Ac>l=^XHKglAOyNq|VtOA<5ZjCyja@B_YYV+(GJ`M@vX@t_UYlWzNqg z2}#al9Hh>>zc{Z%asWt`8?sWzNqH5|W&!I7prI zI}(zd-?fuQJ-;U*$@zT;sdJtxA(hj56Q#Per!Fb#3t`rqDDzRap3VU_pYS#6~5|pi%J5XQND<4?Ld85ex~kWtvA_Gv#vKwP`3Wef%>v;mY{6?c{qx)zm3r5t#>+5U)H-MC|mCiq9_VIzuqH3+1lekeOY@YC|iGFN6otaQi8JeUI*&SdY=Sk z>y~g7Wr6v6zXWCL0}j-e^+5^B)~$Bbtm{J(l&#wws4wfo5|pivXcPszxPY33UrA85 z{@Q{1vOX$7+4`6rHS78t3Ch;rI#6HM$0aCRp9n`$7MQP3N>H{wtQM0apkf3aR%Ypi`zAZu7`c6KI66@#JcO@uW z-*ce8tbdfCZ2glRHS7Am1ZC?74%C)R*{l)lt5goA5)>(jqAQEpek;m1`+Bv2Cu3X<%7zIk6_om_=~CPmr~=3 z$KO-s75(@r{>(D|1nM62%cMo)Uw{)P&WAM(Pr##%U9i1z13cY$8a#tP(z+0-0yymd D^IyVb diff --git a/out/production/RubiX/com/rubix/AuthenticateNode/SplitShares.class b/out/production/RubiX/com/rubix/AuthenticateNode/SplitShares.class index f4b1264a2e07425b6dca2c25a075c9f1149a8189..4b9c49111c59fabd564d30b33474dd862f625a17 100644 GIT binary patch literal 1013 zcma)5TTc@~6h2c6ZP&^jyvyPRTU6$SCm|$gAgNg?$s&oqO_yOi&30xpJB#o){4*w+ z=(|74`0W-HBOyNQoa=mZ&UeoK`1$1<5pB?m8dVrAM`p-v-cu)hD|daVor;8$yXH{x zFin&T`@+hsMpZ^r192>PB6Q5Vy@8Azqv;Ddfr(>j8P$W4w$7-k(xZ&gOrQ)eR4!7* zJ9|4}5p!~wGMW!c)ZD3rZ&@o&1C=?18=;D|aJiL?+Lz^QjGSdTp|eWI>zla8G`XzB9h?-DxVXNb)>dpu0_)rF$T?^)ER^SCfI#ayK9Lq}>-N zv>1(vL~M`ACzXaL>M}Li5fL%jK-lgpw}Vm&^$!1L$6R1_6?dS{gb6^&=gIV_Dm@& z$epD*ob&Lm0hK{|Uuog}%&pIK=R2$l-N!jzM#ks?^yVmw7RiU@p`M4xdIY_S$m0@g Zr)d~6#p%|n@z$h&j1mvC_VxL@qx4|^#N*&Mo>Yh&$0KXshW@YU)JI<@2Ub3gPy=>O4ar_$e90)|J;Ozu7Ro^#JV=XZYhB)`A>2L|2E!=Fkb(EYP-UUwtPJO5I3L1BT#(_SflFb8@xBbhGFY;m45JPy10x3PFe)$@ z#BP}{i*huK23!eKatw@#CDm7DPKPm$jCje)azbpb8F1ympn;qLPl4vy;}Z%Zi81TC z70-K4I)2D?t;vLw^Y$rFGW_-^&{NrbhUTi}x(ccjS$8x(mdj@1$NKwv{R1=(bUGQw z+fS=l(;!`UXGd%WWeF!^_vXiwwmV=Y)7+^{WK&jp&~hDF7dAETijz|iOQf>naW|iI zZp07ey(@Ocb5fRP_tICqei4YF)f3i)pPT^!Cnv$vOVbKL_B8zuqB%)+hty{g;(f_6J0HU2XTm&E4(VEFR+hT9@G00Um3V-;vT*>@eS^q_!bXL^rDYkTy%~9 z$VlmS0T zV;bdH#UI&5R5HCP##W8Ph~OCIlc>cIbr%u!GuY33nh8fcEra}S$8L@W&$jaqz?;-E z2fT$noOPbsi+#*+70#d&ZxfOI+&_uHENT!iP;TIW0hOadE@G<4+=tzJQYnh*nTFwpfZKm)z4%)oK z@|5t7Q+St>Dqx|-TER}FIXfxd8mKRE%LkwMhyOywzfk6uI8J?lo)b9X z$I&-e68ythgcz5eqmF1s_i9p%$~96AUG1zV=j*kRhiGfAFO;IWUK=iyBC198mR9u{ z*3Mwv4BjBPCDXHiNd4-ypAe2}&#+#K`U>4<{t*PJ7b5wpnP&rO*MtM4=s}{;$vC?( zKwQof9YIY<-9+?H`na@{@}~;8T*7I;1Jn=!p*%Y=sVrSVqvvBp=qPg&Txx~2KB?2A|N5S|Tb6PsQXN}=U2SDO@wIa-itg@meBGD;6fDFS|N+-9C55(gCtA&w}D*Sr4ao0-om&(5dM?>+#)9Nf-9hQNd`ny!qh{FOT| z0>uIqDc1|Q=2Q#WTFOC|z|a=mrf!1nV+DOtd#A-LEeuZ%}y~dktB|gYPlq4XU{aoKT8tgEiG1$F|n$%;C*YNbR8H zB^pw{&PokYo8EGK8U#W+Rpxx9`FVWul2fQ0Egb6Tosij9N04o;N)a-tcW|q1@>(R# zwo76A0mp$H?FIcGE<0+zSBfsE^WN<0w9%E|pOCY2_6g;o^G!F#=uMbeX ze*c#m<4uaVsni7KQq*eKuYJYCG*Q$ZrK!ZUU#8J;;qq`(xisXix4KxF^}KeXv~y1y zuDBoAI#AgQuY4AoQ-R8XOW^pvb64wO9Krh~Tkb`_YT43Wi z28W?99{c0bf&myrt07#=z!Ag`!_gRjEXLa~0>^QlMa(Fi!0SnzO`{irqx~Mno(!LQ z3uiv!EQ9_5y_zTEa2~IH2?{R2MVw8+C79S{m_mjOt|bhUDGW0)gTYKe5&wy2V`uW} rY`4_1v*0pZK`&PkZ{jb-u^R@f#c(afvurVB;07Wya1(Cra!h{#?VvrH literal 7266 zcmc&&2Y4Ju75+zU_g1Ttv(NS^aeQ`MWXaMwN}?o^;~=+Kj$GmsF^&m%eYdvGKHZ-0 z_AEPeaDYGxB|s=Cm|{AK1d@?R0n>YjP(leUm=Zde5cALM-svv7`?<#_?*q^+HX0bfZ2@e>8+E)%$D1YimH=+Y9XjqbumX1(cq@)+c$)zOZm+wCzScT(3aQ!L51H=J>Rv6Wx|grrnsEwXI>&s}J_41;W$h zHTk`J?W~>HZd(aE%Nc=#+wEM&N#|^VS^m6~mEIR6k7RluXVf3eJK6m3S|^|8R-#{^ z$-~5w`_h)1&vIpGz{&25?$0^t=%(1#EnD~Ox8tsqFGcAoyC=HhTcqh8m;QAE%^tWT z=?=w)tgM}r9Mx&_ZZZ|^%Vw=31Ie7^7%16wd8Ik4O7`;4u$t={y)C8>Tem8iPP(h9 zqt@kDQ_{6gf(L0DNT%&A`QbfwcF@|BA|^QC#I4lTRyHZeKC;FgN>a$yfw(gq&F1$c z4@cKZ9j0^nT(qBjla}jbizx2j6fe+YE|tc`vs-=n%hlaLdi=mc2SD#tuU*St_SE%$;{qd)XF5I{o6Lgdi$3@iJ3))j*;YV zKYz4$ot4R~KP;Vg=3Z3wkd+&vYbR{iN~WYH%Gr8S3h4QqolRTAG=kw-Z`=Cy+qqs! zC3(*fkhE=Ew+{-Ku5-XnuPba|`dbZ3EIm4>oXj89c_V=aZnZH|!*M&~CTVbi+yBRAs_5=BHS?sVYfM?gdlJ@Sk7<8^u8HXM)Vx>~HD^o;M!j9W%H*2MmIXfXS z8l7y5@(w`{@$-d>rK0|OHT;=eR>f0(tQ#>WpN-oak}|UA&J5H}83-m4uua6VQ{Zd{ zc&7^R&SEr2m^|Y{c0!<~5_JQe+D@2wCa%@+7ZZQQ-vl~#d1opzxi(U1tljB+w+i(@Fs-&L2(zyQou8TWY^8fjAm#~RJJe@(O z<}u#O?=N0$1wwy1llSjE?`|_ii#S{II7c?~O>9SuF&|rVZ!P++z`06RWzzn%YiG0hjB6)K zCd?`Giz2}k7lZCStBmReXqj;fC{HKl;V7{5-@Doh!YeW9F3yN|Z8kqKIhRc=%33B+ z>`2bFhp9$K7BzlElTV4Qn1Hp6EOAoI?rMKFyFTL)~$b=-1g0V5;awbCwge@L>J zHe#`&3UI5!wo5CWq0*w7T=F_vmDLI>uxfIc!QaophUgK!tU|>q&dcVhryKuYDZS(z z+wXiitW>%%43Gs(yKE#apPN(%XIBg$nSg zIoC0b(Vzk=cNI4;?tLwxGz(nT$B_}5JR+QQq|d*N1THB(pKtUMP579KLN2J}xw7`! zV!I~Re3fuTsYsocGq1uz0UR3E=8$8x_BH}tyy>lw*M>|#hDVs>9D-(&QoSYr$a3fx| z%-OT-!*)FH+H%oaXL#63%W^WXu5YkU@!%oFI?J_Gh2JS(O{DVJS6ivPeEU4Jg5GC3 z(7%JJ=w!>LovbhK4za3A($(!Pd;mpD5ft-~olWjNQVd6dEB||@or_-Ar0zxadK}DJaa$9Y$qJ)S6KhPdR;)8|BW@B{JbfW0(}(yV@?ZMQ zY4m~(R-6ylBbwO28*adH4&?c?Gy9qDvTIXTE+^gdw$g+8JiH2XBRxH3=N5YlE2N$h zpDkNB$Y)fA>7|c{q9td@zm|`LSkjeO%c2>?0rkA0c-CI;Xng(+myW*hzdy}W9<_|< zDX>%%Wn`tM(wO$CMGa`;3V|gvlu*e!W%Xs*F1{79kYB9^_=!$_u4A>XAQsW8XH~9x zmdfmP`EXz#kk0}3E%NcB=zLlzJj-5w%d-eqVGloa@o`1CjyS%x*zV;h%3iRqZJU6& zM@`-5PXfQE4G}iI2}oi;M*$o_%3s_~#`0goD5~_gqApl{cd+JeBB~&nH1dNX(8lk0 z?L18fhB>N+Fo0_Gn?PdK?WsdRVKGeL%YxjXg$ncYUZnY}|JY zkx+fj?rt+|a2yDklakdqnqx=n#ql!_dGomPtYZj|BFITKq55&mdH{{yl!r$#`(A{4 z>Z`lWkjcR@^oGpthLB0Njp6!`Ifc;9P(xd&t|P3sbDzd=%_Qak6POz#y`gIy^NyO_ z?WEM)G1MJD^LHw56yZsF28GepsA>{t`=hWlRE;v!9?T=$&(S8j)c`fOnVQ=|?QWy# zuA(ltV-=lnGvOFtYP;!R8TNs1Yy1)6_gunumLiu$RzbLeh0l z;Rvo%K6DDtAx=8oDLj`_)+p$Cl(AMpFCf1E z@DiTS;HqI9#r2f$rCjYrf#kb~e5EU|hIWSHni?9_pP|~#8eS$eaIi`Jy__PR#^T3N zB~D|(KPBM?LYD{d3i8k??FMYb6@Hk$ve}R~h8G*v7U>Ou_$i&Hr7L*OIOg{R!hv?x zD|-?h4ou=)Wz%rroR-~cDxG*ifj&v)diGz~GKEDugXeM91Qy3ev4n`FJEyR0=O`Ao z(1ltjuzUh-B(;;YqJZw0K&QfWh3Uo7QLJo{i@D(ZU9nF~U;ABQH%aT7M3=v1mHu`q zNjs&#fIirvq?=@r;sh?*aa=IYyC)f^2woDrR1r_0r^hH_drPqOVFp{cR_$;CtKNuD z7B-#4Woo|@SnYZLHDP*wRZXI+hruMnA#ehhA3yUKhC@i3q(4D%8AsoaQLG8;EnYB= zV=c!NHf%~^3(~IhrNy9Rb{8(F$fkJ4!m{;+W%ElEFoS4Fi;koJ9_hE@LGgY1gV$f- z_Zvx(>GbvVQqcS4SF+hm;Y*oAFJ$ssN9xlVUm0fTqs-AaGd~|=hMgehJ|?)&Fy6k) zxOo&Kq7K)IxpZGP^`g=#74YC?7~rTfZtQ|c&WG^FBiAaS&!ir z;(d6fxF0u*&*B#GAYMl)Un?HMt>R%yCGUuv(MUd<*pE=YNAU=5A!KmBuj5sO>S2m6 z;?;x#TvvHE%PI)H~^5dD1j8n!lAsP3KXF@Vg>l7q2g{B}G z_qvMD^I$xNn;Dd|E`A)l3sKr=GWfdxhVU8xx&=jVg%%+nSl*7mZ<|>{pDT zUG_`IutfHaV_4a&jbZi_Htn3im177`VStbrL#;m{IEBr`Y#GBEd6md(RVWj-F|B~f zR!11k%**qbjUzaRhMmuwcmXe~2>Mt9T*+&#nyQsI=^Mn;*c%XHwOB7M=gN0+JjlfG uZgPDOJ-M1m_e1>2@kdlUrP}*c`*GENQ?=h#?RQoCW7YmtwZByDul@xCRKY+1 diff --git a/out/production/RubiX/com/rubix/Consensus/InitiatorProcedure.class b/out/production/RubiX/com/rubix/Consensus/InitiatorProcedure.class index bda14d24d196c619c3eb86ee2511cb9ad4e6bc4c..1d3b01525986d5a8ad50b458483bd833420c8a08 100644 GIT binary patch literal 1645 zcmeHHOK;Oa5S|Tb61$-(fj)TF@7^Ms1rfflLz+CM(Z`4Df@SoY~VCgTyZ2h2=;JEBQ44K`;h^h6Xf zMWEv49&(lTI9}uxfg6qH8G+)y=;1|f6R2GkdZ3h06<8zW+i9wp7V!n^Irvi~kE!7z zb)*tO%o6?5v8`^OIXsa<83)U6QAxu-YsDhk9XKIPQ(>HdIa8Xy$LFQbp>m9HsAEQw z+14LHwuSE{nKC1M%5xqKRrZE+*skGN=%9ZAWJ4V`s!)SX6k}snx|w2X9#7fPFbSCI zQWQa^aS_t^j4GbRlg*;(b4{S(E!In@%$0E3Yd$lll0bV-1s)eJm*?80lDnOgL%-eW z%&*fvxD1)h)T+y{O#EdiMdVyR^ axRY}|p2O7~a}^L%fT!d288jvwJ3j#3>F9p| literal 4211 zcmd5=P`75<(V%~&39@|H=P;xvh4CvlW`Nm4sa>ez9t;Kokm#tkX7V`*wnENPUP zksGs>tt)$hQudt^pg?VKj6+*?XxR#s@jTXz1;Pe*<{h0T?`?mY; z{qDU_Fa2x%c>ss-=OFs95JUpW8h%nCN*xuh3Qr0%Di&q?KnMa$D&AOwUc5cqZw=x>yiI=I9>hEF&LG}}hvf8!I+ zuZs7nc)yAdsQ93YCsce$!H0v`Emhl%kJR8vd{o6#L3|7!58@N}q}=IK5`9{t&xB9` zN5SV5d|sf&bX_y$Sw=!2G;zsTG{OlZH5ZP0j+L4l;)Ix;;tV(A3RHSlT%eZSxamZ# zxzt$!C2cGvY=iRF3EPD~VKl8k31!o!YZEKOLhH#A|{VJm&V8#dBbI5IUB z9g0Zf1dMe0#z-VgFET37W@Nnis84_sOK1Iq z#tnC#Gvz?BAmGj$jwxAl@gjFp&K`_PfkeFp)K@_LIaD1tJmVlQCfiB># zo$T%cEt`qv8l&WHH|X>SWU5fors?!paSh+Zw@A|H_;6oO@4z7q z&th4{ik!S$koWd$IE(=ew_#AjxA7eftGK3MO~ZHPx$C&D;CmXL!}AJW(C~fyKtsP= z@Ix$XI3m?*E|Y`EXqV2T53_8Zl0@#@oJ>3;<+&SaMdlY@#G6dZn^a|4UU^Qg4ftFo zNwa_~&4Ru>=x1bYQpD$|ywi^q{8+6%v~$t9r8g|&`_E|y6co|&cAkymwG*{v#skcA;b^9}v?U2;Xa zdvgXYlxo$pvxT2YwyW$>MUIT76Bc769%b=0!+wux+m%uQjfOnfH{b^fZCTyb?N@;! zPUa5^B+S&D#|pxy0qaCjT;6binKm6-E5D`66LK{}@8af>NLhuOS;?u=L#!hX^Jl;kGC<6BnwC(#EQg{-*QrdBrUpMA?!E8w;+<1 zl<7g>v0`PjMjI+ax=oRn)xOLuKag*D43sMp|A8M3vHZJ>xyzGJLX}z)3eAEVs#sp2c=_Q+P5 zaq=x;x;wKA%h{pi@a)2AJ_pK7zgT3W0uf5K7~%6LYI)|6f-0J< zV1E^Dm1}5U!ImNkPj4TrFA`KsK|_&%3bzk776}w7XzJ0an7)Fo*KyN@Yq)tZq=!P= zma$bTKzK`5SE7!bR)pL2+T8H1zS8-%&3bcahhFcGHHUWU4LP(+Z_J@iy-A|$*v-Sb z23zzNJ+zAM8MeGwH*K;fw09Nz_UIZ#0bSA6)|xf+tYH5d!Yeqy3ClRJj)UN9XP@+6 zrSHEdu#;FvHMU|4{{wd5X1aPCA4jjD_c}010$sqZFtGzE?1GCz@Rve+r>DJi76ZxcVk%G zhZDlZs93^D@d!@&TzVzT7o7B|N#4QWqy=8U>xi0YgJ*D&;S=JmFXJAfX5RG2mz1?m?Bn>WH1NFk>h2=a&dA?#a^p!x3~~2y$XB?;6@W#a1*8E9BpT%T`Llj zzbwZw*S)Fe3?h}Vtk1Nt^*vrtI*eh@qZ3S^HSjF-h)^@Sq3R?d& z1n+{ikFfD|g1Lod4KV=wa2w0!#P{J2+{GG!dvO0R28)|AJeb1}&ta(Gob6m5!4}#o Ha&7(uP^c0f literal 4680 zcmb_gd3+pI9sj;$lbLKMO}a^s1qxf~k%qP_SA{JgX+!8jnx@&<8V>7ZcaluAnc2?H zq%CKys8AI}L<@KzDpfowG>NIAc!8)`Z}C9ITf7w%M9TNgOtPD9{@@QkpXAMNe((2w z=lA{In|<_!$p-Al~MX?)u6kMg?Y6aIsVd2_3vaXA9-9AaZ zJ_dn(QtS;X-WY|AH^oqeo1)l{H`n1Ucxw#Rcv}<+yj{U9Q7pte`UbZbJvXB12- zIHKUQ0(I_?W9YdqZ$u#0xkDe-lX=}5OlDlivJ<&g(nkz(&B8!Y zt}yMSB$Iliv0g zVx4wY&u`ToQ@)4Hh&yD`pJkm{dnD<2{pRlE2HPqcR?#aaw|KVWjZDAO#cId1IJQVb zf;#7yxpmR*tWj`H+oD`Uury;1TDt2wl&mQZ>GG*D6{Ciev9rSl)3Y#8U>R;QQ#K*9 zQ4B@qm5KN)PF9(8V^J`{Os@9^1`Nl@^{^s_BmJ~JDi6J*KsSrxvNVQ1!r8g9av8&- zY`gC2QqXn=lRJvGmAoXgxodO(4kPPQP#HAbKq9)+&&5W)IK+DH((`%4O}8`9oRKvw z*U|H4(a1?oZNV@cNz{{T74@u4iF|Kl*yg~Vz;2+3j${p!{O)j#q8AEXK2RE21NukD zM|Icewpk>m&S!USf6qA?C>VN;1^WE=M+4s;PV2}jO{sDqr;T7Z$7S+Yb0Pb zT!J1A7o%On202`W4hf_vI>4ae~cu8}JfSTG}< z(-RuLBn^HUG8^k{+buFhg-wP#Wao+vwfKsPuWEQ0k7)QB+EqNN;p=#Wdo4Q!Ne$n? zBPzZrr5;o8Ee%KUZ3W-aa3x-&;=7XnJq_QNzR&l)JRVsx=pShKA$}xq!sW-M<;p}` zR)W~b2`rcjeI~dB;!_i8tKfy83V^5Kar{^s_=y~TT9&>t{Au_Zo{;lD*YFGcQpJ;$ zn~|>oeo}-{M2g%)8h+*HAq0R#Q+2ONCnEuls(U0$&1`HtbM+Z#uhsBtJf`9|Dt=4B zT~bhys9bI4H2e;~Co^Z}6#PNMAMuoiKS}97Q=8@G^BVqwzY1)q%uRsYM4RUh5%OkM zm&i_Z=tNj9v1^U9#!UqIOl&e_-yvk@Na5{)h=#w(%>Nxd0?Yjz7LBaunC_lrm!0vl zLv8s%o3BG7(|{2;^(FKrg2`9s_un9S>~9FK{z)OxJ?ds;t1PaO{fHfML?1TTgPHDaOpffvu5P(BxqLQ5Wes`yD5`63>uvL` za4!j#K2%-D_BPddYPrW~f~{2ufpcb2U8#9xB}?Fx*%BpBxGuxpWjn*{knEMN!O&V} zv68OTDU(-Tqdi>BQ}=XH2~i$T7LQ*s1;kF@5;+MXm2sUri^WQV=~)9){QBkTccdjP zeX7;{X2I>-5-unKMxHXvZdr?9C8xw>KP~kRiY^M>I&MN5X(~;Hr<;!@>fY?R)BQ)P z2z{WA@)>H6msHG{k&0A#6w0dt&xk1vGw(6U$}C@OyNR6Pa^n{h1CBkCkoOi-cWoyn zlPqC1wUO$1<;Z$@9$`VJYOT~JClaom2#&|Fa=xMlArD{wU@JrHRz2?-g#Q&Usg{-1 zt>nyF?iD2*mvua&i?^#}IfHvPJlIQ@olF0Ju3aWDPv(=#JDBRAH3%%O%p==UL7tO- z>S~Rho}OoxW^|+QVzZJ;BgSr%yS*lxw~K~?f60^cKLSfjZPTQ*jq6qg1I*HzY`j5A|l@1BA& zi}>Yb@>7wOu|gFacvs7quCY$Re|gcZh;KIEW?XS*xDv*ICHw?xw z8Gf+*{m_^C%C z5-e>xgl0*}DaoCbddINf2p0Cq_i-#rMdQ&i#8Y!98au(CJF)KwPU?%#8N=dnoIH+G zQrZzDe8!S-yew58*T!&aU#j6@`gZJTE{r!!G8=*BWqt96aV$^Gjn9p(7(+`+C9zTx zbtGCP5h1~VT2eJ6R!O2ZUK6in9I@3CSd(g$DjO$}^i}%Nz8r|19y=pmH-R%#^QKv6 zO|fF}SbQFps1rE*cBD>=H%?$}swrL{Z(>ZL!_6g!n-eaiz$A zFuE759M7cOT5359b8t2q=+h#c$5ft=RfO_-!ljP@9w1mo2qTXl0{aP<1JrO2!FE4E z_8?*QFu`+_@Oc~=Jc(XBg{^oN+e9t;L>!liRk%W=aHUv}?IMkSu?<;~Lrz%m#7>Ng zJ=i7oVz;;fSBaZ&wYVAAF@kHvt+-Yk!1X??pTGk87@>t;2x?k|SJAsBu?351tsTu6 z5G~k-S2LOsv4nnKM*00Bg3ECQQF{Q-$nOEv)8nJqj@J^vckx=Qb8Q2?y$$`O8tJcx zEU9_)x*s`GF)S4$Fi2H1!U<-hoqjyYUkL_D)iBz7Fhr^rtAqiQl){WWiXEg>+Ik4X zr0N(=jqiPwmDr0sdEAuZ&TylSuo}10Pkv}wkz=?Ka}`{u@P`NaFH6l)!9oQE1t%)} zwFCcSEMylyZ&>-l~LL)=T=>-_Nsf4tEjZ}!Lc`Qu0Z@m_yC^dfAI`3e94 diff --git a/out/production/RubiX/com/rubix/Constants/ConsensusConstants.class b/out/production/RubiX/com/rubix/Constants/ConsensusConstants.class index dc8c209664c36ede48a8964cf836d7ae849d25c1..df2276053fe1faed562daa8d1b6fb26ef10da6fc 100644 GIT binary patch delta 389 zcmYk1%}&BV6ot<~g;J~H4=DbV7@{of)&(&!*n}>Gq!Qwe%s_!cTVp67Y%uWw43FZ< z#D$4lS3Z&Pwz}wIX6`q0?m2g!rEe+y_4ED#poDx9F^0n8vye?fVo3M-m}?IAx>`;2 zt(L#YT+CAp@w(k+kSbTV6&Y$!@nMfaG4--;G<4Irma#@MDi~5m)u=cBv>Obv?b-gn z{>G^4&AXbZn=&#C=hL1w_NI@miEwOT*@F)6x_mZt+Ot8Y>pe`|f#nz7)<}4xu_FXS zq7=AYQq<{LgXSpTw=D&6?5fCOd-3u#M;`P_zgt3%R)Q!=6oX8xM0lBaCBm!3=?JeA vZ$@~FoLG=T`wls3AyZEA4Y}7aVh=b8J3tfc)0Ik^V3GqI(#dcX%8q{l96&y- delta 309 zcmcb>(##@y>ff$?3=9lr402oy%nah}3=-@Nk`sL_oTL~TxC2A|gF=1deLRChI2fcE z8CX0VgFQGHWEdH^f?STn*Y{7#N=+^Sst(Ca0UB0VnqO3!>yudw6k_p6EY1MR z08M64WMBe1ih+TJK@x~r8G!Zxc}xsICo*s#@i~EfE+jrTkk5m}=Vf4Y2Wkeo1V{=1 sjnD_uj6j-IYdZtuMzEQJK#~nC$ig55Wb;52FbFe<0C|iIqF_~G0Fx3Y(f|Me diff --git a/out/production/RubiX/com/rubix/Constants/IPFSConstants.class b/out/production/RubiX/com/rubix/Constants/IPFSConstants.class index 43da9c41dff93c8d958dca4f27ede0e8c439c3d8..c30a5837cfdd92c9620619080aa244ea4f3aeabd 100644 GIT binary patch literal 1149 zcmah|+g8(15Z$5B8;6TWQSpLByZ~CNctN3ph=OPZw1~c@ZD_-4lddEc{T9E%l?T`I z!4L4GT<$ZapilN8J12W)&dlD^U%!9+1W?4s6#6VoR{d5X=v3U#g*D#`BioC@!sgC; z`S_GVzlG5Q`;%R0+Fre|T{&>7k%eT_4I{_1pi3uYISO2_zGNY_?+1r=P_vL|&$lh8 zkf#=ldXk(D8=a`;A2K~zvz?aDm;S(M`xXW|Ufbm{A<{g8wL6-rdqW{(BBpzFd&3%XRv~N1+ZF~T zy*s|4<`f1Eb*I;>5hPcy8g5=e8SZ|MqdK{uB^^Cf7&6?W<5tO;q(y~cLliBH$X&-` z3cai_V(6#6JnAdNGlfw@Jhw0=d4|a6eTtqp>PyhN!YLECS{3TG^ z7-YKIQaFtyTPnGpv(;%;oM6|kG##@^e${U7*@0`$M<0_#@iU7A$_j5WMo*)LORuL& z|6N{gVz%sef~vFb$_@Xl_MBN%rv>S!AgvRmPlEJBkopT! zZb9lQNErpGlpuu>qyWS|ZqgZy@&2wuCEY*i?J{LI}IGPzQ%h5*U+6=~d zn&4VZaeby4lP5Dz=ND*fkshwnryZ#RwnpWT8Z8h_s{^y&@$TfBq{&po(Qa@FojitGV`gx8gpIX8FNG6 zIdfCs1@ooA7IRzR6>~@6HS>)?h51%sm$@gf&wMBFo>>(*V17vAFo};EglBbKyL;qo zkd@sk@G2 z)q_aN)?7F61J8^t!f*BBQo3PU9k;)e*@&0ZTc+P~o%Yvw^`;g3b87XjWqE#78ZFZ~ zgEbAqbMuE95}R(r(vYv%jF);q_|v z7h}_P{J?Yq-`LsTs-8YkCZb$#$9tu#ZqKV*Tee#HALAmYsl&is4LTpO$Wa%Ybsa^_ z^fijK=yi%ZuCbOBa7I6CH8%qVZv8XXHPMQ5Z2(Zt&rVsR= diff --git a/out/production/RubiX/com/rubix/Resources/Functions.class b/out/production/RubiX/com/rubix/Resources/Functions.class index c6dc4ee9beddad8bf6b9be7e88f4420f8450137c..cfd0d4c5b193895fe1a0a567516ab1e8acbc1fd7 100644 GIT binary patch literal 14229 zcmeHNYjhh&6~3d`mgIMy6lfcTM`M>XYLoPl*o4Tk94nC}MGq%VTFgqC$Qw($Vt19q zK+78n1xkRnJPU1zHX~)q>S?8FX^u&KO zyQ}%`y>nl4=kEUT^$RZmz&O0>2OohOih4C{)C=m_aE6+C-6&EsJXP0Ph4TC@msSL+r%OMo0F5S)zUBJ=4;ZkoV`ggZBD8LCzuBhZ&i9gZcl ze9Dl07oCp8ll)0vB6aX!EW_`Hk46%SSZ-dRI*^Xc&BT(q28n@8EExc=;1GCChmqezj-*?2aUnX~VPBk6P^9*yMUDO8O; zwJ&xook(SHrEGd{J{!wS#wVSdqOP4(%W1`0AmA^lhI2I>O(k(T*?e|Bn~UV~SptJx zteM!%L@a|3HYaqW96n|0TKG^lm2`}XhU%S2rE=L^CX&WUo0d2ThbB3C}k&Q%4u2(p;y+_io%>QR5SEKg;vddq26F_friv-O*gC%u3@KAQ;G|8XGJgXITb1@ znx(v4^ata=HStms=DwSEqP}x0y z*kvuKCV{Pqj!hdpi1(P(npE*vJx*X-=VLXVs;sI9 zw#tmXg4o$2t??$&1c8nAiC)#i@l^940_$-N#X6qj>6BWb(~60`in}B_XyqVb8h|MR zQ#(U zarch}0HgH6RcSVlw%y?9GJ8fbs<``T_N#?asa|9$*RfcdQX@Wz8zx#WZK$U)Akw<2 zvYiQ2J0>wqV=TW78H!fYtBwEAo%VZjCx(|sEyiDoR;aVJ;g(xb@U02%Z-dy8E-vEk zi_6hjFf(7mthPu|pe-ZuhIiO6RJcE)q*gQd2Qd}UGN!^M?q%C0f{IDEk@%dn7p)rx z)vUZ#%&E+kH#9bI+Z}PAqho&fBqk#}72sojxk;AgQpfX; z$5}f041seV{PN1y*^aj~mNX_&X={*OYidJMW==8buK<6!P6TQqJ* zjuTH)#jqx*f<=Zy5_tPfQ>#iy~G~_$CpTgYSI{ zN^!AlAc>Nli11OL^Ma4(C65(aOSK#yJsyB3iSLmsX>3p7u{LQH558|$WnxgL6*gqizu64)8a=C^df3(|R@FX@|&~?kS45h{^zX1H4kiT8)ihIMx zj3>d-?CjGGd;5rJrNe5a;vB5dA^Ht0rWF&5cYE_$&n7y-cT~l~{S3z7fPO~9V!wpd zEf&WF+8h-mM_goFtye6yR-tKCW9TsXB^_oRXLLq&9 znWDs4a?ddC30ZAGh%FO?nq z8#vz^`M8xo5ApkLe0&=p-_FN(@b$eDZnEXw4kPwB3OC#1yX<)fP$N6w7X00bPxqj9 z2#&qaL3nP%ZRcV4i+JaQJMg#1{$~%|iP!zkEVv8y;$0B-H7VR|>$gE+OhVz9O~Gg5 z-n{}`NxqkQE(s}tpX(J8eq=1-CaS{(EFAKQ$fg;7p?D}T`S6G3b|0>{$P!jmLdZrQ`{ae75VL`xk zHT_+p7oX^Vs`ohY?HBl+f<=K}$N2J1FT+&?oNEV(K7APhR|O4yKu1PCs7ZY2{jK`( z-6P;lumrwt29w0K?_L2{Z(~Op?qLCU8qP@h$=3OVfIACI+}ByIcB93$sEoqX0)-F2 z?E+_4!!n6q7jPeJldC1Tb+-z*4=vkWT!}mS#JX{T!o6^xAhBy3$x7EfD&Ri60^E}V z?j!I~fuE}(8Nc%a?ql$A!8V_0dSU04zA8}o6nvUfxHucS_PxK=lh^%Spz&FFpbZT- zTYRpSM%Q+M#uwnhHZ)xAOXTR97ifGD&Iwv{aS|5O5E-@oO1Q z%>0j_U%SwtcP>lzKM52bgYODn*LltV5^&$Uq~#?3-u+*J!sAH6 zVCRU zH-c{G;6igBar3u~_k9A5=i#?PEV~q3ZN1Q{W&bMzh2LTJmSx3`>j=2JwhvyiYq6K% L4>+<~<(2;dbkg7; literal 13126 zcmbVS34B!5)j#LW@@6J4+dzN;0s#a4)4f9`uTnIYr%`@Yipmix}V_bmUj z-N}pZ9e#$0mTGH!bOSf}Xg{y>@_KIe6LE`=)^V$c+kA8>Z_@c3oj2>;?kAQ{KHlOZ zFK_jchdVuduAek+@$h-F#&$nB_yP}qz{3~H_Z=P%>D=X`DKcpacYEk2AHBgnUJ#oe zx<&52KJMdw4~ONxQ|Dbij_`nw=5SP=V)8U7s}1`2B941G!AapP{KNpVj#}AAgCz?BlQSQ4c?_^9w$@f}33IRl-$&ZMR9>E5gxmaut)Ka=}(6XJf3#WGdbmj+(8h zfi5%N5$cLy#J@4t9g1uX#l!M$4?2_m;RMsnjoq<<`gp1Q|?F zd(F7nv)K&wm~pIKYEy+HW@9XxG^5zXC;KHD;_=X4rimM4@xJ<fY578ni|Bt=-dY4l22H{%_o1vjH0d_Z9sPs7*2L5 zgtfX;kxEyEz6_#EGBGpIwIm323g|S|(w3 zr|@ZSeTzlCMtug4hCO}t-lPezXxmo*was=X}J6kA(iy0x25hv5$ZK~EDf z%``8cCdTmtO?!GlzX`~PEb^Gf&_s(E&Laz2qaZI3nvBa748eM4M@&eVf_e5Fzh&0Q z>R2pdhN8<=5a|geLoj@3aL|nQz=4t}7(N^GX=*4!ZEI~>l*1=D)Ov@+eN_;%x$hJ% z#qIqG*gayd!B!pdP&9#{z_g<>uN!CaX{mVm_>t!ELwW636gRug@NP4{$u#5QX+DT4 z@oMcJID>OA7RRj^W07!oNaBPQ%iM`r_bv&5rPe-CGg;rRhD6SA6ag48kT{fY z9SlHHnAtWSi}mXK3RaT16Yh&P#bX2Q{h_#cms6YyT7^b>Vgs9E7%J)wM?(=jhE>!8 za}o*_%+E>1;wkvD(Ho8@lGt!J;)S@PiJ01xc{dQ|<72NA2Q5PQs@Z48)k=$Cr#!=p z^A9gk(KnuKi<%;U{njxQv)&2^L-Axsf84ac7A8O>v?_%Oe|Q&a`@LAbD|&mxml^~H zO$ql*XZ(M$Y-2>AtnGvbeF*J?>CGlVHIihM*s?)7gLnj(p=1m&v>}^Hh9mXO_9$$q zN6jI@E9?^+6k4DICKES=4YJqO`MV&3eYb`pDY5JM|D_E7M^H~6bDKnXU@&5;Oqof7 z1rTkZF*X3ZfK!g;Ru&mDN33fnZyqMh6?>Y!Skk2TqWN*{3D=A#K_GBb{N6;g02W6;(9aO*AKpY*4`GHY>13o zvLG#uDlY95qo^deVi3zt$}L^@4yMajJHF>Gx?;RMtFTCwHT?dxX)%P@)>1Yf*~?~= zdL`r`L5gFw{rB3k-}~BCU2d7UC{vu*NxCuUR=UmL3VK-Q*9`g- z{h6r*IXan0#zTWGX0kullPGrc_dNW4gMUD;8vHul1%q~mk!FSx2LF(M1VyJ)S8k1t zXp#OPyQixXBYV)pKNcqL!i9e#m!HD@TSDC){u$aEbR(%f20cV*!G10be35DC_KXY{ zRIH81WATb$MPn!$jU_8!_X??l5;YZV?G>#uk{XoEZ1ymb!M~t~fv>d#gUP)WmO}jF zTLgoD$-grA*N~QOqMHr6g>KgQHwOQfe}@1z)E^5Cgbn^Z{{iJ;T9$D|y3T(z_)q+2 zk?Ai6zrk-B{8ze7=f4^Jcm9XYZyEeg{+GdT^S=!~&i^s!5Wi#4H|U!Nzbn-5@d>8M zYJ;ps&MrUUzKaYEM+SIUXlNQeY-kS6DMKzpbMu=gDc>rebWJxjkLCqan$OS*pm)un zS9Pt>(2BHTDG{V^9IH_f!WJz)y>21?w@4sr6hkZ3{PKMQ0HRGaxQeR{ z`a9Pd^j$*Cbs&Hn^b9>~@F_gkpcm+vM=OItwMhouNFPV$>x|l4P zj8()s|TRL5$fqNw7J?mrc*LxR`q}hyUeJ>pENfc8aAW)*rIBSo{CxW&!f#} znw3G1oju3p97C(r762zF6J{DxgWV#>)O-Y1f;BjxRi*W=kbn{?HYDx1p;c=&=}#z> zo7*yJlxgnCOWMq-WSF5dv|73iiisuaq9|q!txgQ452DDe4fp6;y`e4CQ00}J3`AX9 zESxRTwNnl4G;JyLnC+S3UKML3yP(*qNTj-@1@28n(%j|-R1~#p{p`qTXs5#sVDM!I zKLqPyGuYIkQ);losiB=Aa4-K~&mwXJu=I+!mC=xxBcl?g8DqlACh>S`5FsRsV4fn# zw7#ve_EdL&L%K=MBAk%3MS5c^E-GQuWnx+{xy4Wp+tyiwPYY^@@Ln92G_@^P-d)?KYP$z&TP` zWAOaVa-_rOV+xL8>ZHtq;_X>>Kc*VK31ee+cPX`VMSa6q7nG>C7OT%$Y+8MPY{0DN zJRj@9s}zZH5(TG2m6cs}O{qj5pGT*n5s;=!!z`3+MzIr?<0T)yXI{#3&T8yoEaEix zm^h=DpRFQ0uV#0JS!Xw6P_YM5YGJ3Wga8AjcM~5SJI=v=Q^quy{Xx{I46r$fH!9Wury1p9|f!3z(zv)Rjk$%iuVXs z@D2#MwsbUIxC~*-s*bXWZ6Yk>0W0?5&kUQ7e1r?+V8|PiGrR8CAkOWovYEDAW_fm( zo*rrzExF~~MOJV}%xIq+fw+b31{9J`V5Jf7)^P+=ZT7l(jA{*yo$q*(nNG7HDW^PX zbd?DR$Lww|#WcOLas2q$dQO3LP6V@$L(tiDS;r`$)CL*Qs zcO1gzi+jzRn%Y~<ZM79WE7@}KTxYu1)zylk>_zJobsf@0XYO`XDFK8`R2 z)wUkMdiEE9A}}UY&KKDs=Zx64vWz+eau{& zRp-7uTUVLwa*ir98;!Y0hOiK2m(=9w9!-&?nJMVjF@i zj!=>a6ILOrCQ8gvT`y`r(BKCQGal}?oyiHWMEJDGB>?rJG^tl@0#m-mcKiEcC}%d5 zcG8*x57@NGYO0%i*V+I|_wl*YCD}R?;fo>Iq+Bc7g^j=z*;|RBYb&G_J_{BZ(`q=n z8h;zm&O?M# ztciIJOS3eSGqD5Bbsq9;P3A#`y+mUu5^2Xt({f!yxSl&szI?pp)Mz=Z*fP*8+D|v& zw^;{yrNzLLSK2vsM@NTy8L{-gxPAg}^|+%+Bv;iT;xFJqquX(HtHH^12c8X!fbOJE z;>}B+qPswa$$S%eKuPq8ASaL!xX#p7VPXrVGveudxsGw$q zCbbTe8lH^dBQ#}O?I8*TodKs~gr){v0hfQ;2u**S%JDQqJvZA zokD(^OVel`1!+DtQYCfK0@_7YbUoETuXUJH4;3w>`)DyeOs7H}r=bTtoxV!T=w&)X zsdSa4Haegz;-r`8Zag9P(U<5R`m{2_ayp1H2j-X4y;#kORm$iybU(Rh7#x+6`&|m^ zbg53B`BnNmRHU9ii%%X*8=?p3L0Ai?2$r>Aa)+3Q7LQVef7S@iKKlsG*;X||ryQcW z8%3|xVict>jLz$<9-;YotE_z#vn*W9#@Yn2y|e}ltfd*$1huS#8rDPnW{AB(30Q@l zyim*|^f}O%L4?oKqY!WgO{6a<0q0OLJ*ET{j@?-QLGbLQ$LWhUzjs1VL047vC@pBI zdW^tSb!+W2PkDmQS_h0*`^+fS)YOhpt=Mps>c;q-s%Ca#g>$Kpw!wtwfrsrd-}zYv zsG=v70k8+uECz7FxQ7UE#;kIBk`6;>6KFCW!IKlS-SiZmTqHa@LH{&3MuU$hai-fr z?ZCYboYp_(+vr$1U7ilojH>A)w6J91J>;vN?r0k(y?VN{ZJ)-&Cw^8fTw73^K{}rM zaP6m33Ik?40lWyn)(`DQ73US8^+M;*0V%Y%;mg?3akA~M(EVe zVX*B#O`i5S!Sd?>#?q6y-UDRprRj7rIKBkjeu$Rf{S3M+!}WCN@vGq4C41A?z^fp2 zDZNNvx4E7{&J*x47x>m`k#LXD^bSqqN3ei?`UMUtqiX}^3rF5dq zb?GRb9&`r~kLn?luexO62rcWZmH}I!m+}d8HJG~w0$mHmUI+iZ9!y^Y*x!%=_M z-2;Gs8jg7|BZWZdH3cCrzI~6r4+T%QO{HO0IsE`qI25ePNqdh63j{1UrX-|Ot>tX4u`vBeIj=nZn0|t7y)>16N(s#dL)0Af z1U&Hc4FMg=W?RsEjNHQ~-jcV87Nbzc{dfb*^lMvelYWCIi3TS979J)s$W+P2i5)&bzr$A- z_GqTx(;ooWMNr`%0RtWT&6D$QfVG9D&|g63Rfeu4?F1M>1bIVQ_)@{C`hO$RjgE*9 zzbwRnQmaJoA(d_3Oh<42EV#g*gV8P3B^9I8(o!S0*4C;~Y706g2M3&zgrRUr!v0N2 zyKqt$P+-640hcTD;t9A%>71Z9pv%n{@W`#8HsBql%|W9!;FEh{ZJw)xEN4;*Yu*R@)F8^gg)ujF-cJ9-laBpcvD3}UKI^dGQP`)0&cd!ofrjm%JdURV z@U;kB90k~S!MWeTQz3Yqg$Q#LyIu@;cn_--gWm~s0#7C2+CT)l8S9xeV(JL(?A)hgz2C^xUHR6FV9)_oq?I$Elp_(% zO78m+orn$mIb9)@atY1kQv7M6pK5plE#Zl@jLWEjC($`Pg*rJvT|A9qJe~G%IbFsx z=qjE`H*p0W;92-RXEuHmnuFg?rqR*FIl2fK0)pZQD?S@wr^yol7Ay!9JV%M35io$S zq~Hxfrchx9Q3iQSjX8%;91G|#&}3P4`7kwNVO;|M?qNFJ9;=tlu(Rh`#HTFUiHK8r z08J2R5#=yHQ1mPcE~{eM8*n}fE5s3AFGir4N(1Qcth>|)2hbVZkN5qsro0!T@^~7w z)_sqSybThVcn$t;bS)L~I-1JsfxKp_;tjNh&!)4vg|>1lUC3>;lh2_6-i*H)T}Pk5 z{V;a`VVmh$ZpUAkZOx$OY~a_y#RxcCX(G^kGxl7Aa;6lBE&$Ru@B}=0P*^weL?GLX zOnfiU{e58NSu}`~fpRHAk7dH;F<@T8CB}HFLXA94!;{oNUx6n`xP)X}4sWn}pew2H zgg_^qoU9auYZNt#PAQ#k(CH!oh-lf{=ut6Lunw2?`0oS)WAXb<1Q+-RDgyRX1t?2V zGmj@GTCMX;H^L@M7Dr@2OXI(IlrE7}gR=*DmvO!jw6ikxT};VFG)>YXYP%^C zL<21~k`h~M{U1bJ8_QMr!(S}03(AX75f4D^R!1Pc7M8FT>7q%>!Ehi0W6y?zX~;G@ z&jC;zC;1G1l>}1)94R!#9P>*(^pvl~v8o&o2PsfhUboa)tvZ65@-kQ3K8M7>8euA{ zW#Nkv)h?l8{veq85b$*=&~XXP<;xXbq}!cH1w0R>i4z!hq0o^wz=Jpc)~dj%|b+zv?=ic74o}McswuO4;|vCR-5&AKq;*6C}m;2q~a-Gt9lGN9n!~4 zJ4kD5%3M`ti2n;m=|gR`Wv)_h7l!I~l=^P%$D8lg9qM%lgdS`QILln1sVg}vQgT** z+ddaWJ|cdYmU$k~Onfb5z7A4dPk!Ey9_0qA z`%r`hiJw4?GXh8+QVd$>SY^Bffh4C_;ZylE(8CY-Wf)1?f#<{_Thdhl8kQ@NMLrUA zTEIdwvEI=c?8AqT26e|$g!~b@vP8d|+E9des>=}n72X1Fz)gm1ymSPHPvdr*_ z*DSC)RoDq44iG<&sPO`##xa`AU!xiPBHZljw2;4n1pZAVfN$Xs`Cp=s;Qeao;C_Au zLH|{yHR(E*Ajpd`J%}L_c`1qqH~>bhwo#s}O4o&R5=rh-=|0BG5PPHndw|d2Ab>D~ z4l1C#Xg=Km2Mz+P3+YB)&MN@2l~}PNL%$027S)*ew0~*XN}itXX5T7)>di_+A0blml8J9kx!X7s%wY3Zd2Fu)%6Z_y-Qs`|38vt B@Oc0L diff --git a/out/production/RubiX/com/rubix/Resources/IPFSNetwork.class b/out/production/RubiX/com/rubix/Resources/IPFSNetwork.class index c19d656e82d8286903b75e6169af9fb3f8814efb..c6c664b869d4b7d6f72d2396b1397709ab480759 100644 GIT binary patch literal 4776 zcmeHK%W@k<6uqs;(IX0WoClCVGUky;0W^>ZNFtM9ghgaz$%TxofYnITmfD_~p6Y4& z@gXeu3|3SnRj^^jcd+6gpmJxVNKL7wj44$DRcxer+;i@uZ}++L+h31<27py)q#!}y zT8F!)=(pLC`4tU#Uvy|-*0!px29<|g?57|}U}?`fuuRADx@NPzM>~>0E;zJ=yCx-d zeY_<#0_PN1op-xb5J=YtS7idHSDDA;eFCTQg&hLP3b$zr&JtK0v#$%mMH&{#!tY;u z0^@NGsBK_~K65O|xM%o+w;k#R_l#_2yGIS?`dmnZi*C{Ktxk^?9o{YN86C^>xHQ_- zcuI3}`$6a$DnoL^GUTyOvze(z+02&UJ{9t~!o6MA?F&nCp<$cB5zCQkG+&qhvrY8S z)aCw1s}Q@u^EaGtA}@d~mdjX1v5OmvZGJ}o*0|=DVHR?5E(aM{CU7xdAL~F%3g&go zp-wE;nMWIaw@t;ig-1Vu8@eqPlhVTcPfvqIi)EU&t3G-4Hk* zsq@eZ+XzJ+i&M(i88?}~8<=k2k<7AfVQz+3Yj}kwWer&x-Xie*>}o`6{QSEWM+r=U zz#UEXN10kai{=@9Zg~R!^UjUH84UZO74({(bBsy&44d&ryd-c(EcCqyajHwhLCo&S zD)VeC{{gP?T^-HD#?n*=8!Wqi)S-SjW(6s@g4p^FxI{1T3tMfwAFsP$3~quxkIA?SWurw=iUS$e0_x; z(N15|aHy_u*R?!5zzN;Q#X-l{r{^1u>B9pw4WAQuG<&sP(B_>!I4hGB_MoN=C<=c& z-)?QC;UOW(|8AbKiV@2QcX2EFimS3vE0>gSvSQfuDX60Y4ip>@k4+W?sI=SoDHFg7 z;9-Q{h6z;U1vrgY8Aw4I|Ig!_3}o^54BnN{ir|0tG335ke(5Jz`UUS2Xa$H0-@F1B z@HaQGf{Sno?=tW*J|8gLM1}-D8!)`8VJJonp-l#^z-tOFjBq;cfr5J-uExey72Gv2 z6dbyn;crX9t-u=!Zd{=^HTnIj;NFJo3T|AN8yegn3a)Sh+@A{WCcG2ZAGxgH-aP^C zwt{;vew?JC;EG^km%NYlPhz|uM7G29t?PNTQG zP*%K;*Hy<7C@i1A{b$6lSz+>n!tek-RpK9e*5Q6saBJ|H7FW^K>#>4chvm39Y}0U$ j4|Zr3>pWhm@@S>Tz5K&M)&BAcRbwf9 literal 7152 zcma)B349dSdH+A{F{@<|upmIlfN(Gf9jrvSEExI#Ee!WwAN~Oy*ta1 zHjbUxNpq)3o5X3;y1AUhZE8DI$Pg#aQQLKzI7!nwNmI8?Pxrpt^f384`8Y=LV1oCbh~p?enSjDW20k4}1P?aietag5&*I@Y zejUFNAr+v0v`-d4w+L^;Z_3>xa`$K)op?-!&&zPZz;7kcfQxY~$Aa*AJdR7a9LE>% zgn=&^_(~jWunh8N@bDE>x z$07V%90&35GW>@u|7Q&UB@aKAhyOP4KL-9+A$mhPn|Agpgxa^9PzVp?rfh{JL+PwN zQkt8z3&*X=3}+HUxs;VTVHMKy>`jK9nRHQM!%!+Wmn@Vf)8~@M>|(A|NZG~Y;OL>T z5!*SNE6ny&P9|M+?5sk2`_P@%87rBwvZs?{P9dE=-9K16C14g=`FtjwvYd2|8xyre z#GB6*90fI~5Gxh!Le`oi*tp0Z@&v{Yo=e$z;ZZd3e+FJsFs5^bvsPhBq3@NUsTD2w zqIugcq{(HG$U9W#X%@+QZXlP<+9_h&Tt~!EI+sl6r;AA|pVo%z*T$DAQM6{2?kQLm z8Y014p5Loh?5GtUzr}YrlM=6(;0h2yCzh0dWq=>T_=+YYkm1*3n7|fRM^&>#2JOh z2s2OLk#uzx>9AdxC0FVs5N%-_%BN|hMh*Y4Rh*$`M963^optO&P?pwph9s`8az`$v zP}6Y?REMTnSsnA|^X0ftUS;JQd|>tX?j`5NV~&-Y9k%j1a|~QD7==nHL`qo=I&|8m z`x;IjpmD}%oPwRtDKxkHoU0-wm8MkYkP)DYc?J3nU0|+{SsT2JhMelLym6zaMRP|&Ivb+=qGFGu@(`%;Ii@bzLM0T1esxHQG zkbfm*Ox3Nn##B-u_86+yRNDmQt8tI1wyPbc+NpM#c%!=BP<_IwKc;Rl)gHAsrfxLV zKDEDW%0L+xu?J#mz{I=MK|>uf)lKSfObrU}BZj)!R6}Zqp@vO0f|I5?DlyfVoJ?nv zlR8%$x>JUFt*MTwF;g8^w;1Y#sm9fEX3BV)weD=uRJV%xCvePEw+WAvGTbi1>u^$G z)zv497lkxK**?{A$H*-&3}*8s$E`eWOq%NT>JHKAlnj=sCdDo(#Rye#Q`rJyTJ2C+ z|5HxCDpR@H%4G889`(;B##BXtK`B{5S5|eol!H9c?n(4r$BoSuXAa~t z8J2zNYM39z8J1HyO_zK6Rdz{ZVH9m=%(fZ1;r1iC(OH$?Bj? zH1iU$fPcUkXRJ)gK01BXq2jFvx435j5l1t2_O!$3YAlu}S)Z z=|ZZMc6`s(Z9gip>@leef~ROLA0;$fPDm-4Z7|N9x2hFa%$ZC`x^Qt1@nmpy&CiThP$7E_|Fx6T%P}>5#X{o&M z%CJETOS{F+&dD9HiuR7(3M z+*Wnq9V=xWrWH9+vj5Or6@1<_O%s-WT3%S|bi~29uk^x!bUr@AcNiAjNHJsEJRXd* zR@&h!BJZYb7Q)M`dPE3;gm+aJ80Mcx4>39{YWa4llL?xwo7fOv^1C*g^iWe zO=r*KW^M1)pWbDNAF@(Tu5jK^OxEa7E;n1E#XcOA?rm}#{KI@r$k@e=E@gjhSqRKj zZ9L9bxH{xP|CYnImc@XT$&95PyWdcJGrO)vp?cV=I=U(-o(|Z+?_8t$Q&yZGyZAoC zag5JNUKOvAj*C!_@}>dDIY#y5O5DPG(cRxEZ(Oby~y{yqhsHN$x$x^(bd7Oma4b zDNk^QJmlk5qPwHD>yj|+3%7*p$=-=Y*o9@-tz~a_clojtzU%~SEt@9~Xyz(q9oMagSrOLQKq0_N;MoZ=25#;=A6o&HUarMDGn#ff23lVHciOjT>pyH14FSWAx-KGE`$J!(t9untC%$l%pfU zqT7C7w&8c z&tq*!tNbL^^+iavEBYALuZ*_Ym(T`UWkXBk0Sd@^8RXDvTR(24~5o8C!7<=gDCc*5VEL8N%$uYWyr$t5tcU@5|>s zReD5~jsIIikq(WA9y9PXo5m zXi1u_g1-lMd-!{N{9PXYIB~xT_mERF-Fq+jMaXHThyTr#C@JZ#y@hM{ab^|N6^e-( z=rnMD*uYy2yiIcR6#th!_jA6w-}BV%y;@!B+g@MaEp_$1o6O%teeWT@dx`eV1o0MD zoBPni@6i=~dwqR-eSN!qeK&jhuJrY7t`44O4ZeecMcqL{wYP@Xqa1Bwu zhc#juQA!fIC9xb;{P5*sYlsn>6vP)6ux+U0F}!*n+aJKr=o2(?D6wN~BAnPcHWBF< z8(zS!u6gVpS%K>p(BGN3fs`LXjDYuybJ)wxH|nVkyxXVmR`G7XzFW+@1H5|xXD(xa zmG?EnwIcd>9PAPo?-myyWNA7?H_zjyi#U7{gMCpcu16+Dp2G4jO1yczD={ROhpxO> zhSMnYd&Y%uSZ?@gf?Gcr8V>nE6D);DGLTq9bDn>R+SZhlU{4OLJKsw+h~(h z{9it}L--XwHQ-nAWnQ;&zJ*#pN!>n+`<1jKmw3IF*XMZM&FlAheGL?UQJ7P+r2aL% eFNTkC?c;jEA&yOG(zNAK9-4|x$|Bx$MJqNHNJ!=(5-K59V`u72$uBYgUSI$E5)^la3+_&H8Th{}3jDX$)oK-sAD>dy#WX|iwJeGDWNG67UWD=1b3aiTfMY8Fps$h5= z{n2Q$&9|4XGi(h$zAT@epWC-_mm&WP)BdX{48h1OY$9K%^0up2^EWK@@$i7gt~Q9F z^GX#3DK#eB3T%T0k%pcwh#P28)S%cyyUGB&bjm0jd`9r0-}!{q^QvZz)>d`0f=`?@<31*C+K{Gg3VAe1(}zprwlsBH8tTMtohFn}l8G~_r*UR1 zdt4DDq%OK*!GaA138{)e*&$$&NTrko5(@-khg1n9R{R8{B9-u6J8lwO72?d?bI#oJ zo$oyE%nyIxe+VFs=^#Ql6vSa1k+-87;z6j=qT*NpFXQ-D?mHR8DZC|I3wUc zVLP^WNkdD}Cc*^K8Ft^O+(pUe;|ArLKjMccVC<_5sB z3o9^dWv6bL`7(1=XUq~8eXsN?GQ?~Q7R*?yZ3+6)JHD~jd zbHmFqp^LocdEF#H)-5|8vDIXHgl+I$IhUN`b6>^IZjg#VFyoesS?jzlI}mwV%syF* z5W+B zQkcz*1hj(Wmv>0H9xowJq3*f0s%`Il2C|0NWv|{8=vXhk?c8$bthHlQrGMVc@)#~? zc#HK-x$a!KAP^dM9IKejo28P)obGPqu!d0`iwiu)d8^b>bxhPv`bNtp$FYTiweev! zm&D`-gzB6mHs-blku>x9jO|$o4O0U9>+*XRH-Wb2@53H6@&zgX6!2ss!g~|7ey)P6 zuX_dJO9~B$^6sw~6>Om#s&2qmY@-&yb{Mos=eq<`xb}4~qv1g?rJQV)(jwZrTbH3k z58gwtr&UQWLF;K%({~!g((3O$U(iFTL}`OY+0VPiNIG^AeJ_c=Nc{jw%INLf8^As^ zBSvnFg&k<&s^KN`?xKj~;E)~DWsrY=EMdNwMz4{XvtLZ~HR zXeu)fNI^;8(U|j!5^q%Ep-rGe^0`C}7>(+5ypdkhhQIJJ_8N^*{T_jWMyLuzK}l1Y zmJp2<#QREIH<-a9PAl=S8jn=4qxvGFsTJL>U9?J;yE+e?!oA=lWu;)6v9%k*ES#??O4%WMewLQ*}vbe{g#iRZX z4&q%5;5NU$@8bwQ#8G_05Aza^;d6d}S1^cgkid61f$zEJN2KrzM(_xu_?2h*4_v}y zT*fNW!iO;t=8Jk8#>H+-ROa9=d-#aB?c@@s#{lEU*mw4oEOwErl=f97LP{N!8la0- z?B_fw2#XjeCdOH477=vvsSi6v5M8wSIaPn6o05i~ah3VSn0JQ&r%=vh51I8+3Nphb z?u~IqZ{t%Qo)}MuoWIYoeU%RyIf1o*RmgGV+pb~)nosllx5~ZG+0-CJ>VNDB`Fu~9 znrLb9>AqE_8LkCo^tHG$dX)g4ph<}Rk6AW_O_E1^0FzvUJRsL_9dEF;gVc5E30^1u E0gNyT#Q*>R diff --git a/out/production/RubiX/com/rubix/SplitandStore/SeperateShares.class b/out/production/RubiX/com/rubix/SplitandStore/SeperateShares.class index e241e653954ab2325dd20676d94667ddd8fa11ef..417bdbc249bff71d0496159deb2127fd0f1d8a21 100644 GIT binary patch delta 459 zcmX9)Ju?GQ6g_vd`(Cnw^${x(LJ$!{W@09WL8GBS!7$2224NCKMoZxjWcCLbm6j$k zm~x;OZHXK9(=#3(VKEEkhJD~kh z#F6knBwc?^%Ub<&u3yT6_N|(CaJufDZ+rV^C5@!Uh@Y3yON@YmToEwnQHZF?^0Y#0 z<(ddT{H1MTkOmvth|&K7+IF%CI?%~T(EQGdz|K42f#Vl@!wDD7XE=LJbT3$;qPjzO z+{z^jv6Px=plA15NlZ<*V&?Jf&sW@Pz`bX82)2J?xR(jo$Z-BFl>*(>|JfKol8h=C z#L(X^^GMM%m@iMyfU_prGL!+&xEE-!D{y@DSAhEG! z(+c7T_yLx-mi88yTQ`|AGv}T;Gi~uGmfn7zUI7#_Ye6C=5x1ZrrXZnUN+KySO%RLK zMzy(2&{OGMg0XUXRBqKTeFUm;ta){cd)G7{3T!vs!;=m7Y{xyQmnA|HVef+yrVStb zt*;Tw#tc$6(#W&|=|MuU=AOIxy4yI;ZynUihfOa`DQ}(P7l=XdS?XyZHP2{qm*-5J z%}fXM(EaXV6kSq>&9(h6Kmfhm`O$|UGivx9de^iR^o>?ttj(aWXgovP??7KL^`dY@ z_SG>ew}?6sGc#6jM6L~E?@G|!?`Onp!@Oq~9X;NSHhd9d&n)}T@kX_GmA!{ChJFn2 zJwOSA2ys@G!<;(1gdwgpRu)(rR$j;fgc5Ph2_@kav*f%09tflJCE5u#jZ#iarX$$Ur-l~7M>XK^-iyw-YC(O-rH z5=b2RQHZeS4iaeVxoVY8|XbdpHJ;06nCpP_l6GG(7oUVrz9 zp?;{x(!m9W_8H_;W3+M6W~}ojGqTX>i5zp9Dp#qnN@qMbI!fiNc+7ooG?84*a&0Wv zCK-ra#1lD4b+R|*vB)xQc_jHyn19b-jJ^VjTg?Txr@8dKKPLI!Yol{%?CGJ--l=46 z1aY|nZ4Jh`Mm}1&)PjdD!&W~y<1DmBWyyZYX**Dvd^w**(u@Sr#Lx|NEYc%kR2eTX z>vp0FhMi#Tx@l#NqEvy48w~kh?Bl=wFGDMl_QAtPmAYu$Mt_$C=3<+nw|*GX27@2! zxrya7Rnp*Bq8yZ@Ip~oV7h9tqFH}(weIwdsfgVVm^d4$Na|2ECJUDRa+@LQWe6pJq z?Nu@0e?seR_u>b1zEoA0$u=pc%)dgmRrx-)aFrqt*U()e-2V;X`U-?jg;1;NZsOLt bI=WhRzP+OE>#w>R?oeh8JGe_{oe=mB%Tx!{ literal 3173 zcmdT`O>7&-75-*+$z85iB4ul1E4CE1wG;iMqGcykD>;sBwQgk7W*jPZWyP^qJ-SKy%xFjP_!tLOMxOlf*xET>^Hl#MMa9+YXQy9 zdvCt?=FR(~{`l2{Z2&oh77pUHg-N`U!Wq1JfYKQYKfn)_?1F(Y15OGD@FN4SS+Eo~ zgIPsgv~US|MO`*-6AW^Kibx%NBSeO+^p7v{gc!uoo$Tb0dCMfePo%d_r zmFC)_SD$kitCSqb2PL<9&8_>2ZwvLX;x`1I%a?++Y`wYYzmqMlSN+hfm5X6e_hN3E zcQ%w*z!}c3xOd!a)vYaOi(%cbEl;a!Wo<%0&>gWtrb))AMYq$s6RR{sznVQ)ue*2i zej}t!@eZLrp>l;Etr6ChmwU_;c!`+kt)-w@3)M|Et~IV@o)k~052eY_TU%FLOi=R7 z?nmEUfBf*#{d_vzarta5^p?H)^cgzZT@2mQ>ScF5ikg8p1ngxmoH+GzlnFjDF+36_ z!zu>Ndda)stB6}sD96=VJ}I}vvqOal*srmB}Xq<)ZnowX8D-E-HbEv#Tw z;K)K0p<4{(&AEy<)bL7mFC6k4Q$s@F(3-pI%>=cQ8(#Or3aJL`GGw%$->(Qeau++v z#KjTYeK{+0UAaRNML+bW4bZ#ed)~L7Zvul)$KhKX zt_L}F1yZVsNNJ?mjQk!Zm*pFOo#vDDd{w~sE0~xb& z^tM*G2fIz{1)f!N`i2zuTAyra{BD~$J!9q)=5JxlYZ>!HYhKd|^Ey|8E6HW(g?W=J zlT;sa#d)eIAbFiD!L<)iBQWt_fHWUlOnx&^VRo)I_6HKQ+sCP{&L?$xO4?BH$gcX3 z`~P^7?dVS8W0-QP`w7+K=wsVXqN2pVLQ2b}SO;UK0f5$EP8E(tZQI?P3XrW#U*WL9p(a{P zNy5M+86gC4*nEVp781~7p&E%T@h7C8U?`x_fcfN)2=pS;fl#CN$#Fzjz@e6!qMayS zxCfQ`H_j(oFgua-Y#(HcBfP_$0`c8DZW*jQ47B*>uc7u{`oEca1Y1Ss>7n57#`p03 u_;-W9BPv>K2e#Y&C~iByIS-lSDas_K5pcJNUBgdMW9ytHZ<0U9b^brV`G_(A diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 4f340de3..3c6e76f5 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -23,10 +23,13 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; +import java.io.RandomAccessFile; import java.math.RoundingMode; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; @@ -41,7 +44,13 @@ import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.*; +import java.util.stream.*; import javax.imageio.ImageIO; import javax.json.JsonArray; @@ -49,8 +58,7 @@ import com.rubix.AuthenticateNode.PropImage; import com.rubix.Ping.PingCheck; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; +import org.apache.log4j.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -2103,6 +2111,7 @@ public static boolean generateMultiLoopWithHashMap(String path) throws Interrupt return status; } + public static int readTokenHashTable(String path,String tokenContent) throws JSONException { File filePath = new File(path); FunctionsLogger.debug("File path to add is "+path); @@ -2123,6 +2132,87 @@ public static int readTokenHashTable(String path,String tokenContent) throws JSO } + public static boolean checkTokenHash(String inputStr) throws InterruptedException { + + boolean status = false; + FunctionsLogger.debug("Main thread started at" + java.time.LocalTime.now()); + long tStart = System.currentTimeMillis(); + + ExecutorService executor = Executors.newFixedThreadPool(10); + + Runnable generateHashMapThread1 = new Runnable() { + @Override + public void run() { + FunctionsLogger.debug("T1 started at" + java.time.LocalTime.now()); + + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + try { + long start = System.currentTimeMillis(); + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + + for(int i=1;i<=5000000;i++) { + String tokenHashStr = calculateSHA256Hash(digest, String.valueOf(i)); + if(inputStr.equals(tokenHashStr)) { + status = true; + } + } + FunctionsLogger.debug("T1 ended at" + java.time.LocalTime.now()); + + long end = System.currentTimeMillis(); + FunctionsLogger.debug("Write to file done in t1 : " + (end - start) + "ms"); + }catch (NoSuchAlgorithmException e) { + FunctionsLogger.error("Invalid Cryptographic Algorithm", e); + e.printStackTrace(); + }catch (Exception e) { + e.printStackTrace(); + } + } + }; + + executor.execute(generateHashMapThread1); + + executor.shutdown(); + + while (!executor.isTerminated()) { + + } + + FunctionsLogger.debug("Finished all threads"); + FunctionsLogger.debug("Main ended at" + java.time.LocalTime.now()); + + long end = System.currentTimeMillis(); + FunctionsLogger.debug("Main thread" + + (end - tStart) + "ms"); + + + if(status) { + FunctionsLogger.debug("Valid TokenHash"); + }else { + FunctionsLogger.debug("Invalid TokenHash"); + } + + return status; + } + + + /** + * 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 + * @return (String) hash + */ + + private static String calculateSHA256Hash(MessageDigest digest, String message) { + byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8); + byte[] c = new byte[messageBytes.length]; + System.arraycopy(messageBytes, 0, c, 0, messageBytes.length); + final byte[] hashBytes = digest.digest(messageBytes); + return bytesToHex(hashBytes); + } + + } diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index ff31990d..df9d38eb 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -448,7 +448,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception TokenSenderLogger.debug("No Multiple Pins found, initating transcation"); } - JSONArray quorumArrayList = new JSONArray(); + JSONArray quorumArray = new JSONArray(); switch (type) { case 1: { writeToFile(LOGGER_PATH + "tempbeta", tid.concat(senderDidIpfsHash), false); @@ -459,17 +459,17 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception String gammaHash = IPFSNetwork.add(LOGGER_PATH + "tempgamma", ipfs); deleteFile(LOGGER_PATH + "tempgamma"); - quorumArrayList = getQuorum(senderDidIpfsHash, receiverDidIpfsHash, + quorumArray = getQuorum(senderDidIpfsHash, receiverDidIpfsHash, allTokens.length()); break; } case 2: { - quorumArrayList = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); break; } case 3: { - quorumArrayList = detailsObject.getJSONArray("quorum"); + quorumArray = detailsObject.getJSONArray("quorum"); break; } default: { @@ -481,17 +481,27 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } - JSONArray quorumArray = new JSONArray(); - List quorumList = new ArrayList(); - for (int i = 0; i < quorumArrayList.length(); i++) { - if (!(quorumArrayList.get(i).equals(senderDidIpfsHash)) && !(quorumArrayList.get(i).equals(receiverDidIpfsHash))) { - quorumList.add(quorumArrayList.get(i).toString()); + String errMessage = null; + for (int i = 0; i < quorumArray.length(); i++) { + + if(quorumArray.get(i).equals(senderDidIpfsHash)) { + TokenSenderLogger.error("SenderDID "+senderDidIpfsHash+" cannot be a Quorum"); + errMessage = "SenderDID "+senderDidIpfsHash; + } + if(quorumArray.get(i).equals(receiverDidIpfsHash)) { + TokenSenderLogger.error("ReceiverDID "+receiverDidIpfsHash+" cannot be a Quorum"); + if(errMessage != null) { + errMessage = errMessage+" and "; + } + errMessage = "ReceiverDID "+receiverDidIpfsHash; } + if(errMessage != null) { + APIResponse.put("status", "Failed"); + APIResponse.put("message", errMessage+" cannot be a Quorum "); + return APIResponse; + } + } - for (int i = 0; i < quorumList.size(); i++) { - quorumArray.put(quorumList.get(i)); - } - TokenSenderLogger.debug("Updated quorumlist is "+quorumArray.toString()); @@ -813,10 +823,6 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } - for (int i = 0; i < wholeTokens.length(); i++) - unpin(String.valueOf(wholeTokens.get(i)), ipfs); - repo(ipfs); - TokenSenderLogger.debug("Unpinned Tokens"); output.println("Unpinned"); String confirmation; From 4018e2672708e7ea5adcc459a4e3e1fbd437eb06 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Mon, 13 Jun 2022 16:42:25 +0530 Subject: [PATCH 165/179] Included a method to return the token number for the given tokenHash --- src/com/rubix/Resources/Functions.java | 73 ++++++-------------------- 1 file changed, 17 insertions(+), 56 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 3c6e76f5..d646edbf 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -2132,66 +2132,27 @@ public static int readTokenHashTable(String path,String tokenContent) throws JSO } - public static boolean checkTokenHash(String inputStr) throws InterruptedException { + public static int checkTokenHash(String inputStr) throws InterruptedException { - boolean status = false; - FunctionsLogger.debug("Main thread started at" + java.time.LocalTime.now()); - long tStart = System.currentTimeMillis(); - - ExecutorService executor = Executors.newFixedThreadPool(10); - - Runnable generateHashMapThread1 = new Runnable() { - @Override - public void run() { - FunctionsLogger.debug("T1 started at" + java.time.LocalTime.now()); - - PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); - try { - long start = System.currentTimeMillis(); - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - - for(int i=1;i<=5000000;i++) { - String tokenHashStr = calculateSHA256Hash(digest, String.valueOf(i)); - if(inputStr.equals(tokenHashStr)) { - status = true; - } - } - FunctionsLogger.debug("T1 ended at" + java.time.LocalTime.now()); - - long end = System.currentTimeMillis(); - FunctionsLogger.debug("Write to file done in t1 : " + (end - start) + "ms"); - }catch (NoSuchAlgorithmException e) { - FunctionsLogger.error("Invalid Cryptographic Algorithm", e); - e.printStackTrace(); - }catch (Exception e) { - e.printStackTrace(); + int tokenLevel = 0; + try { + long start = System.currentTimeMillis(); + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + + for(int i=1;i<=5000000;i++) { + String tokenHashStr = calculateSHA256Hash(digest, String.valueOf(i)); + if(inputStr.equals(tokenHashStr)) { + tokenLevel = i; } - } - }; - - executor.execute(generateHashMapThread1); - - executor.shutdown(); - - while (!executor.isTerminated()) { - + } + + }catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + }catch (Exception e) { + e.printStackTrace(); } - - FunctionsLogger.debug("Finished all threads"); - FunctionsLogger.debug("Main ended at" + java.time.LocalTime.now()); - - long end = System.currentTimeMillis(); - FunctionsLogger.debug("Main thread" + - (end - tStart) + "ms"); - - if(status) { - FunctionsLogger.debug("Valid TokenHash"); - }else { - FunctionsLogger.debug("Invalid TokenHash"); - } - - return status; + return tokenLevel; } From f5e0632fcc66e5c5bec8f859692590c026b6a498 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Mon, 13 Jun 2022 16:56:47 +0530 Subject: [PATCH 166/179] added brk stmnt --- src/com/rubix/Resources/Functions.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index d646edbf..61e5c39a 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -2143,6 +2143,7 @@ public static int checkTokenHash(String inputStr) throws InterruptedException { String tokenHashStr = calculateSHA256Hash(digest, String.valueOf(i)); if(inputStr.equals(tokenHashStr)) { tokenLevel = i; + break; } } From 24f44b7698150f7e2348feedd78c3aca70fc2b59 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Mon, 13 Jun 2022 18:21:29 +0530 Subject: [PATCH 167/179] Fixed Dual Commit ISsue --- .../RubiX/com/rubix/Resources/Functions.class | Bin 14229 -> 14449 bytes src/com/rubix/TokenTransfer/TokenSender.java | 22 +++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/out/production/RubiX/com/rubix/Resources/Functions.class b/out/production/RubiX/com/rubix/Resources/Functions.class index cfd0d4c5b193895fe1a0a567516ab1e8acbc1fd7..2c107dc5015130206e83c3feefcfd285b2bdbc04 100644 GIT binary patch delta 647 zcmYk)T}YEr7zgn4yv^w>t8GR^Wr@hPHht&5PGDiD*Tf=C`nWM-jqx&VBeQMBZo)3A zTj5Wb7bRU330jR2SX5TphX#p|7v0o_ghW?^?1LbBERZhF?|Gj8#o-*zxzbZSQ$F+i z;S(XmE-{@iAJFIxo;s@VKnr8SQj3n#O@$__ov_W~L4Qd**LDtTm*+x%NpUs&w%S6k z{qcsDwec=9o;=!ZRP2C=}7!sU}RgD5+XL3RPN><^UI zE$`68w%{DwfxB!c7VDbGgsWcCMMT-_7-a8YwqDUV?0Q67WyOA7(oS5^6*Xg$`&;VqPH0H8&pJ*)e&wmD1lsqq(0VT@aFC@Q_#>*zIA|I&6K%kPQ za5JFjBNo}8@B|e#BFUb>SWwax{5Do3otQv0cunzA-2Dz{`Ea^Cog$+t$ zi2D)Du^(WI)Zl>6sad~5MI>!Oj?E$;G3XMOB8vZrl&WIie`k6IlGRufaIP=wT#3uY bb1{iI-Cb2Syb@|+>hDcnh}T>#g2c-|cV)-e delta 496 zcmYk(O-R&17{~E>hEz0EWc8RKBKxAbyZ?Q8h?a6#qAa>3ks;zm0uf&z2s%_m1T7v? zewcU>#3h0dlNE%hg}1es@#(ReZ$}@B#+Z!R zT&|h4@&nJBTT!&JLeW02E8K7R)P%`kvwSWr1=~fsP!2^UiL+rRy|@)t8N>_r5WcWq z;vb!YMx6L~6j9m5G7VsdhS1WkauN6F4NTEKe5DT|9a(vWt2B>Xhsqj!TEYP>BYr{U z4~A$6^Yk))(d%gFRJo1r&MVT79Q!eR`WgrH4dPKJ@9`j-w)P0`qAD?LbCf|_Ol1!J z^ev|8DoQaYo2ZXxWd}Vph#5M7a$IE;0Z(NDH$AP*8|6z`u4*%bEiWaD*zlZuL{-Ac zPju6LOwa^M^bYEiDl52_bn+cJ_8$CXS6#*5QwQbI5{}r)DqKosyVi z9*MN_SBBHA81(|S@;4SZXhfNgAfQ=!g1hQu9kc4rW&WRRjem04HM7C}j1jYb44q$_ AB>(^b diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index df9d38eb..36b9127a 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -807,7 +807,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception TokenSenderLogger.info("signatureAuth : " + signatureAuth); endTime = System.currentTimeMillis(); totalTime = endTime - startTime; - if (signatureAuth != null && (!signatureAuth.equals("200"))) { + if (signatureAuth == null) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); TokenSenderLogger.info("Authentication Failed"); output.close(); @@ -822,9 +822,25 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } + else if (signatureAuth != null && (!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; - TokenSenderLogger.debug("Unpinned Tokens"); - output.println("Unpinned"); + }else { + TokenSenderLogger.debug("Unpinned Tokens"); + output.println("Unpinned"); + } + String confirmation; try { confirmation = input.readLine(); From f64c19ea718a3b07ce5ff2e88436e7da75122e8d Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Tue, 14 Jun 2022 14:43:16 +0530 Subject: [PATCH 168/179] Handled Null for Input stream ... --- src/com/rubix/TokenTransfer/TokenSender.java | 612 ++++++++++--------- 1 file changed, 336 insertions(+), 276 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 36b9127a..900511e1 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -434,13 +434,19 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception tokenDetails.put("sender", senderDidIpfsHash); String doubleSpendString = tokenDetails.toString(); + String doubleSpend = calculateHash(doubleSpendString, "SHA3-256"); + writeToFile(LOGGER_PATH + "doubleSpend", doubleSpend, false); + TokenSenderLogger.debug("********Double Spend Hash*********: " + doubleSpend); + IPFSNetwork.addHashOnly(LOGGER_PATH + "doubleSpend", ipfs); + deleteFile(LOGGER_PATH + "doubleSpend"); + JSONObject tokenObject = new JSONObject(); tokenObject.put("tokenDetails", tokenDetails); tokenObject.put("previousSender", tokenPreviousSender); tokenObject.put("positions", positionsArray); tokenObject.put("amount", requestedAmount); tokenObject.put("amountLedger", amountLedger); - + if(Functions.multiplePinCheck(senderDidIpfsHash, tokenObject, ipfs) == 420) { APIResponse.put("message", "Multiple Owners Found. Kindly re-initiate transaction"); return APIResponse; @@ -634,8 +640,22 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } + + if (peerAuth == null) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + TokenSenderLogger.info("Receiver is unable to authenticate the sender!"); + 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 is unable to authenticate the sender!"); + return APIResponse; - if (peerAuth != null && (!peerAuth.equals("200"))) { + }else if (peerAuth != null && (!peerAuth.equals("200"))) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); TokenSenderLogger.info("Sender Data Not Available"); output.close(); @@ -649,27 +669,14 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("message", "Sender Data Not Available"); return APIResponse; + }else { + /** + * Sending Token Details to Receiver + * Receiver to authenticate Tokens (Double Spending, IPFS availability) + */ + output.println(tokenObject); } - JSONObject senderDetails2Receiver = new JSONObject(); - senderDetails2Receiver.put("sign", senderSign); - senderDetails2Receiver.put("tid", tid); - senderDetails2Receiver.put("comment", comment); - - - - String doubleSpend = calculateHash(doubleSpendString, "SHA3-256"); - writeToFile(LOGGER_PATH + "doubleSpend", doubleSpend, false); - TokenSenderLogger.debug("********Double Spend Hash*********: " + doubleSpend); - IPFSNetwork.addHashOnly(LOGGER_PATH + "doubleSpend", ipfs); - deleteFile(LOGGER_PATH + "doubleSpend"); - - /** - * Sending Token Details to Receiver - * Receiver to authenticate Tokens (Double Spending, IPFS availability) - */ - output.println(tokenObject); - String tokenAuth; try { tokenAuth = input.readLine(); @@ -689,7 +696,20 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception return APIResponse; } - if (tokenAuth != null && (tokenAuth.startsWith("4"))) { + if(tokenAuth == null) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + TokenSenderLogger.info("Receiver is unable to verify the tokens!"); + 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 is unable to verify the tokens!"); + return APIResponse; + }else if (tokenAuth != null && (tokenAuth.startsWith("4"))) { switch (tokenAuth) { case "420": String doubleSpent = input.readLine(); @@ -734,58 +754,61 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } 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"); return APIResponse; } - TokenSenderLogger.debug("Token Auth Code: " + tokenAuth); - - JSONObject dataObject = new JSONObject(); - dataObject.put("tid", tid); - dataObject.put("message", doubleSpendString); - dataObject.put("receiverDidIpfs", receiverDidIpfsHash); - dataObject.put("pvt", pvt); - dataObject.put("senderDidIpfs", senderDidIpfsHash); - dataObject.put("token", wholeTokens.toString()); - dataObject.put("alphaList", alphaPeersList); - dataObject.put("betaList", betaPeersList); - dataObject.put("gammaList", gammaPeersList); - - InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 100, alphaSize, ""); - - if (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { - TokenSenderLogger.debug("Consensus Failed"); - senderDetails2Receiver.put("status", "Consensus Failed"); - 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; - + else { + JSONObject dataObject = new JSONObject(); + dataObject.put("tid", tid); + dataObject.put("message", doubleSpendString); + dataObject.put("receiverDidIpfs", receiverDidIpfsHash); + dataObject.put("pvt", pvt); + dataObject.put("senderDidIpfs", senderDidIpfsHash); + dataObject.put("token", wholeTokens.toString()); + dataObject.put("alphaList", alphaPeersList); + dataObject.put("betaList", betaPeersList); + dataObject.put("gammaList", gammaPeersList); + + InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 100, alphaSize, ""); + + JSONObject senderDetails2Receiver = new JSONObject(); + senderDetails2Receiver.put("sign", senderSign); + senderDetails2Receiver.put("tid", tid); + senderDetails2Receiver.put("comment", comment); + + if (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { + TokenSenderLogger.debug("Consensus Failed"); + senderDetails2Receiver.put("status", "Consensus Failed"); + 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); + TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); } - TokenSenderLogger.debug("Consensus Reached"); - senderDetails2Receiver.put("status", "Consensus Reached"); - senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); - - output.println(senderDetails2Receiver); - TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); - String signatureAuth; try { signatureAuth = input.readLine(); @@ -809,7 +832,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception totalTime = endTime - startTime; if (signatureAuth == null) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - TokenSenderLogger.info("Authentication Failed"); + TokenSenderLogger.info("Receiver is unable to authenticate Sender!"); output.close(); input.close(); senderSocket.close(); @@ -818,13 +841,13 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", tid); APIResponse.put("status", "Failed"); - APIResponse.put("message", "Sender not authenticated"); + APIResponse.put("message", "Receiver is unable to authenticate Sender!"); return APIResponse; } else if (signatureAuth != null && (!signatureAuth.equals("200"))) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - TokenSenderLogger.info("Authentication Failed"); + TokenSenderLogger.info("Authentication Failed!"); output.close(); input.close(); senderSocket.close(); @@ -859,7 +882,21 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { return APIResponse; } - if (confirmation != null && (!confirmation.equals("Successfully Pinned"))) { + if (confirmation == null) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + TokenSenderLogger.info("Receiver is unable to Pin the tokens!"); + 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 is unable to Pin the tokens!"); + return APIResponse; + + }else if (confirmation != null && (!confirmation.equals("Successfully Pinned"))) { TokenSenderLogger.warn("Multiple Owners for the token"); executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); TokenSenderLogger.info("Tokens with multiple pins"); @@ -875,10 +912,13 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { return APIResponse; } - TokenSenderLogger.debug("3"); - TokenSenderLogger.debug("Whole tokens: " + wholeTokens); - TokenSenderLogger.debug("Part tokens: " + partTokens); - output.println(InitiatorProcedure.essential); + else { + TokenSenderLogger.debug("3"); + TokenSenderLogger.debug("Whole tokens: " + wholeTokens); + TokenSenderLogger.debug("Part tokens: " + partTokens); + output.println(InitiatorProcedure.essential); + } + String respAuth; try { respAuth = input.readLine(); @@ -898,9 +938,22 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { return APIResponse; } - - if (respAuth != null && (!respAuth.equals("Send Response"))) { - + if(respAuth == null) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + TokenSenderLogger.info("Receiver is unable to complete the transaction!"); + 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 is unable to complete the transaction!"); + return APIResponse; + + + }else if (respAuth != null && (!respAuth.equals("Send Response"))) { executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); output.close(); input.close(); @@ -913,114 +966,68 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { APIResponse.put("message", "Receiver process not over"); TokenSenderLogger.info("Incomplete Transaction"); return APIResponse; - - } - - TokenSenderLogger.debug("Operation over"); - - for (int i = 0; i < wholeTokens.length(); i++) - unpin(String.valueOf(wholeTokens.get(i)), ipfs); - repo(ipfs); - - 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); - - JSONObject transactionRecord = new JSONObject(); - transactionRecord.put("role", "Sender"); - transactionRecord.put("tokens", allTokens); - 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); - requestedAmount = formatAmount(requestedAmount); - transactionRecord.put("amount-spent", requestedAmount); - - JSONArray transactionHistoryEntry = new JSONArray(); - transactionHistoryEntry.put(transactionRecord); - - updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); - - for (int i = 0; i < wholeTokens.length(); i++) - Files.deleteIfExists(Paths.get(tokenPath + wholeTokens.get(i))); - - for (int i = 0; i < wholeTokens.length(); i++) { - Functions.updateJSON("remove", PAYMENTS_PATH.concat("BNK00.json"), wholeTokens.getString(i)); - } - - if (newPart) { - TokenSenderLogger.debug("Updating files for new parts"); - JSONObject newPartTokenObject = new JSONObject(); - newPartTokenObject.put("tokenHash", partTokens.getString(0)); - JSONArray newPartArray = new JSONArray(); - newPartArray.put(newPartTokenObject); - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), newPartArray.toString(), false); - - String bankNew = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray bankNewArray = new JSONArray(bankNew); - bankNewArray.remove(0); - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankNewArray.toString(), false); - - String newTokenChain = readFile(TOKENCHAIN_PATH + partTokens.getString(0) + ".json"); - JSONArray chainArray = new JSONArray(newTokenChain); - - JSONObject newLastObject = new JSONObject(); - if (chainArray.length() == 0) { - newLastObject.put("previousHash", ""); - - } else { - JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); - secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); - newLastObject.put("previousHash", - calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); - } - - Double amount = formatAmount(decimalAmount); - - newLastObject.put("senderSign", senderSign); - newLastObject.put("sender", senderDidIpfsHash); - newLastObject.put("receiver", receiverDidIpfsHash); - newLastObject.put("comment", comment); - newLastObject.put("tid", tid); - newLastObject.put("nextHash", ""); - newLastObject.put("role", "Sender"); - newLastObject.put("amount", amount); - chainArray.put(newLastObject); - writeToFile(TOKENCHAIN_PATH + partTokens.getString(0) + ".json", chainArray.toString(), false); - - File tokenFile = new File(TOKENS_PATH.concat(partTokens.getString(0))); - tokenFile.renameTo(new File(PART_TOKEN_PATH.concat(partTokens.getString(0)))); - File chainFile = new File(TOKENCHAIN_PATH.concat(partTokens.getString(0)).concat(".json")); - chainFile.renameTo(new File(PART_TOKEN_CHAIN_PATH.concat(partTokens.getString(0)).concat(".json"))); - - File shiftedFile = new File(PAYMENTS_PATH.concat("ShiftedTokens.json")); - if (!shiftedFile.exists()) { - shiftedFile.createNewFile(); - JSONArray shiftedTokensArray = new JSONArray(); - shiftedTokensArray.put(partTokens.getString(0)); - writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedTokensArray.toString(), false); - } else { - String shiftedContent = readFile(PAYMENTS_PATH.concat("ShiftedTokens.json")); - JSONArray shiftedArray = new JSONArray(shiftedContent); - shiftedArray.put(partTokens.getString(0)); - writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedArray.toString(), false); + }else { + + TokenSenderLogger.debug("Operation over"); + + for (int i = 0; i < wholeTokens.length(); i++) + unpin(String.valueOf(wholeTokens.get(i)), ipfs); + repo(ipfs); + + 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); + + + JSONObject transactionRecord = new JSONObject(); + transactionRecord.put("role", "Sender"); + transactionRecord.put("tokens", allTokens); + 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); + requestedAmount = formatAmount(requestedAmount); + transactionRecord.put("amount-spent", requestedAmount); + + JSONArray transactionHistoryEntry = new JSONArray(); + transactionHistoryEntry.put(transactionRecord); + + updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); + + for (int i = 0; i < wholeTokens.length(); i++) + Files.deleteIfExists(Paths.get(tokenPath + wholeTokens.get(i))); + + for (int i = 0; i < wholeTokens.length(); i++) { + Functions.updateJSON("remove", PAYMENTS_PATH.concat("BNK00.json"), wholeTokens.getString(i)); } - } else { - TokenSenderLogger.debug("Updating files for old parts"); - for (int i = 0; i < partTokens.length(); i++) { - String newTokenChain = readFile(TOKENCHAIN_PATH.concat("PARTS/") + partTokens.getString(i) + ".json"); + + + if (newPart) { + TokenSenderLogger.debug("Updating files for new parts"); + JSONObject newPartTokenObject = new JSONObject(); + newPartTokenObject.put("tokenHash", partTokens.getString(0)); + JSONArray newPartArray = new JSONArray(); + newPartArray.put(newPartTokenObject); + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), newPartArray.toString(), false); + + String bankNew = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bankNewArray = new JSONArray(bankNew); + bankNewArray.remove(0); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankNewArray.toString(), false); + + String newTokenChain = readFile(TOKENCHAIN_PATH + partTokens.getString(0) + ".json"); JSONArray chainArray = new JSONArray(newTokenChain); JSONObject newLastObject = new JSONObject(); @@ -1030,13 +1037,11 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { } else { JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); - newLastObject.put("previousHash", calculateHash( - chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + newLastObject.put("previousHash", + calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); } - TokenSenderLogger - .debug("Amount from ledger: " + formatAmount(amountLedger.getDouble(partTokens.getString(i)))); - Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); + Double amount = formatAmount(decimalAmount); newLastObject.put("senderSign", senderSign); newLastObject.put("sender", senderDidIpfsHash); @@ -1047,105 +1052,160 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { newLastObject.put("role", "Sender"); newLastObject.put("amount", amount); chainArray.put(newLastObject); - writeToFile(TOKENCHAIN_PATH.concat("PARTS/").concat(partTokens.getString(i)).concat(".json"), - chainArray.toString(), false); - - TokenSenderLogger.debug("Checking Parts Token Balance ..."); - Double availableParts = partTokenBalance(partTokens.getString(i)); - TokenSenderLogger.debug("Available: " + availableParts); - if (availableParts >= 1.000 || availableParts <= 0.000) { - TokenSenderLogger.debug("Wholly Spent, Removing token from parts"); - String partFileContent2 = readFile(PAYMENTS_PATH.concat("PartsToken.json")); - JSONArray partContentArray2 = new JSONArray(partFileContent2); - for (int j = 0; j < partContentArray2.length(); j++) { - if (partContentArray2.getJSONObject(j).getString("tokenHash").equals(partTokens.getString(i))) - partContentArray2.remove(j); - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partContentArray2.toString(), false); - } - deleteFile(PART_TOKEN_PATH.concat(partTokens.getString(i))); + writeToFile(TOKENCHAIN_PATH + partTokens.getString(0) + ".json", chainArray.toString(), false); + + File tokenFile = new File(TOKENS_PATH.concat(partTokens.getString(0))); + tokenFile.renameTo(new File(PART_TOKEN_PATH.concat(partTokens.getString(0)))); + File chainFile = new File(TOKENCHAIN_PATH.concat(partTokens.getString(0)).concat(".json")); + chainFile.renameTo(new File(PART_TOKEN_CHAIN_PATH.concat(partTokens.getString(0)).concat(".json"))); + + File shiftedFile = new File(PAYMENTS_PATH.concat("ShiftedTokens.json")); + if (!shiftedFile.exists()) { + shiftedFile.createNewFile(); + JSONArray shiftedTokensArray = new JSONArray(); + shiftedTokensArray.put(partTokens.getString(0)); + writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedTokensArray.toString(), false); + } else { + String shiftedContent = readFile(PAYMENTS_PATH.concat("ShiftedTokens.json")); + JSONArray shiftedArray = new JSONArray(shiftedContent); + shiftedArray.put(partTokens.getString(0)); + writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedArray.toString(), false); } - } - if (oldNew) { - String token = partTokens.getString(partTokens.length() - 1); - String bnk = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray bnkArray = new JSONArray(bnk); - for (int i = 0; i < bnkArray.length(); i++) { - if (bnkArray.getJSONObject(i).getString("tokenHash").equals(token)) - bnkArray.remove(i); + } else { + TokenSenderLogger.debug("Updating files for old parts"); + for (int i = 0; i < partTokens.length(); i++) { + String newTokenChain = readFile(TOKENCHAIN_PATH.concat("PARTS/") + partTokens.getString(i) + ".json"); + JSONArray chainArray = new JSONArray(newTokenChain); + + JSONObject newLastObject = new JSONObject(); + if (chainArray.length() == 0) { + newLastObject.put("previousHash", ""); + + } else { + JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); + secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); + newLastObject.put("previousHash", calculateHash( + chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + } + + TokenSenderLogger + .debug("Amount from ledger: " + formatAmount(amountLedger.getDouble(partTokens.getString(i)))); + Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); + + newLastObject.put("senderSign", senderSign); + newLastObject.put("sender", senderDidIpfsHash); + newLastObject.put("receiver", receiverDidIpfsHash); + newLastObject.put("comment", comment); + newLastObject.put("tid", tid); + newLastObject.put("nextHash", ""); + newLastObject.put("role", "Sender"); + newLastObject.put("amount", amount); + chainArray.put(newLastObject); + writeToFile(TOKENCHAIN_PATH.concat("PARTS/").concat(partTokens.getString(i)).concat(".json"), + chainArray.toString(), false); + + TokenSenderLogger.debug("Checking Parts Token Balance ..."); + Double availableParts = partTokenBalance(partTokens.getString(i)); + TokenSenderLogger.debug("Available: " + availableParts); + if (availableParts >= 1.000 || availableParts <= 0.000) { + TokenSenderLogger.debug("Wholly Spent, Removing token from parts"); + String partFileContent2 = readFile(PAYMENTS_PATH.concat("PartsToken.json")); + JSONArray partContentArray2 = new JSONArray(partFileContent2); + for (int j = 0; j < partContentArray2.length(); j++) { + if (partContentArray2.getJSONObject(j).getString("tokenHash").equals(partTokens.getString(i))) + partContentArray2.remove(j); + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partContentArray2.toString(), false); + } + deleteFile(PART_TOKEN_PATH.concat(partTokens.getString(i))); + } } - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bnkArray.toString(), false); + if (oldNew) { + String token = partTokens.getString(partTokens.length() - 1); + String bnk = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bnkArray = new JSONArray(bnk); + for (int i = 0; i < bnkArray.length(); i++) { + if (bnkArray.getJSONObject(i).getString("tokenHash").equals(token)) + bnkArray.remove(i); + } + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bnkArray.toString(), false); - JSONArray pArray = new JSONArray(); - JSONObject pObject = new JSONObject(); - pObject.put("tokenHash", token); - pArray.put(pObject); - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), pArray.toString(), false); + JSONArray pArray = new JSONArray(); + JSONObject pObject = new JSONObject(); + pObject.put("tokenHash", token); + pArray.put(pObject); + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), pArray.toString(), false); + } } - } - TokenSenderLogger.info("Transaction Successful"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - updateQuorum(quorumArray, signedQuorumList, true, type); - output.close(); - input.close(); - senderSocket.close(); - senderMutex = false; - // Populating data to explorer - if (!EXPLORER_IP.contains("127.0.0.1")) { - - List tokenList = new ArrayList<>(); - for (int i = 0; i < allTokens.length(); i++) - tokenList.add(allTokens.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", requestedAmount); - 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); + TokenSenderLogger.info("Transaction Successful"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + updateQuorum(quorumArray, signedQuorumList, true, type); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; + + + // Populating data to explorer + if (!EXPLORER_IP.contains("127.0.0.1")) { + + List tokenList = new ArrayList<>(); + for (int i = 0; i < allTokens.length(); i++) + tokenList.add(allTokens.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", requestedAmount); + 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()); } - in.close(); + - TokenSenderLogger.debug(response.toString()); + return APIResponse; + } - return APIResponse; } } From 795ea29b1d3faf50e58007ee1592864bb360ae7d Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Tue, 14 Jun 2022 17:49:39 +0530 Subject: [PATCH 169/179] Included Token Authenticity Check --- src/com/rubix/Resources/Functions.java | 61 +++++++----- .../rubix/TokenTransfer/TokenReceiver.java | 94 +++++++++---------- src/com/rubix/TokenTransfer/TokenSender.java | 4 +- 3 files changed, 84 insertions(+), 75 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index 61e5c39a..b2055dfd 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -40,6 +40,7 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; @@ -2132,28 +2133,44 @@ public static int readTokenHashTable(String path,String tokenContent) throws JSO } - public static int checkTokenHash(String inputStr) throws InterruptedException { - - int tokenLevel = 0; - try { - long start = System.currentTimeMillis(); - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - - for(int i=1;i<=5000000;i++) { - String tokenHashStr = calculateSHA256Hash(digest, String.valueOf(i)); - if(inputStr.equals(tokenHashStr)) { - tokenLevel = i; - break; - } - } - - }catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - }catch (Exception e) { - e.printStackTrace(); - } - - return tokenLevel; + public static boolean checkTokenHash(HashMap tokenDetailMap) throws InterruptedException { + HashMap tokenHashWithNumber = new HashMap<>(); + + boolean status = true; + try { + long start = System.currentTimeMillis(); + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + int tokenLimit = Collections.max(tokenDetailMap.values()); + for(int i=1;i<= tokenLimit;i++) { + String tokenHashStr = calculateSHA256Hash(digest, String.valueOf(i)); + for(String tokenHash : tokenDetailMap.keySet()) { + if(tokenHash.equals(tokenHashStr)) { + + if(i > tokenDetailMap.get(tokenHash)) { + FunctionsLogger.debug("Invalid TokenHash"+tokenHash); + status = false; + break; + } + tokenHashWithNumber.put(tokenHash, i); + FunctionsLogger.debug("TokenHash is "+ tokenHash + " and token number is "+i); + }else { + FunctionsLogger.debug("Invalid TokenHash"+tokenHash); + status = false; + break; + } + + } + } + + FunctionsLogger.debug("final tokenHashMap is "+tokenHashWithNumber.toString()); + + + }catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + }catch (Exception e) { + e.printStackTrace(); + } + return status; } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index c535f5bb..a4ec5a36 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -408,42 +408,41 @@ public static String receive() { TokenReceiverLogger.debug("Initating check"); } } - tokenNumber = Functions.readTokenHashTable(tokenHashTable.toString(),tokenNumberHash); - if(tokenNumber == -1) { - - TokenReceiverLogger.debug("Invalid Content Found in Token : " + tokenNumberHash); - String errorMessage = "Invalid Content Found in Token"; - output.println("426"); - 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(); - - } - if (tokenNumber > tokenLimitForLevel) { - String errorMessage = "Token Number is greater than Token Limit for the Level"; - output.println("426"); - 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(); - } - - + + /** Token Authenticity Check - starts */ + HashMap tokenMaxLimitMap= new HashMap<>(); + boolean tokenHashStatus = false; + + for(int i=0;i Date: Thu, 16 Jun 2022 19:53:06 +0530 Subject: [PATCH 170/179] Token file missing - bug fix --- .../rubix/TokenTransfer/TokenReceiver.java | 36 +++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index a4ec5a36..69cb7b23 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -411,7 +411,7 @@ public static String receive() { /** Token Authenticity Check - starts */ HashMap tokenMaxLimitMap= new HashMap<>(); - boolean tokenHashStatus = false; + boolean tokenHashStatus = true; for(int i=0;i Date: Fri, 17 Jun 2022 11:08:47 +0530 Subject: [PATCH 171/179] Token Authenticity check - bug fix --- src/com/rubix/TokenTransfer/TokenReceiver.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 69cb7b23..50f5f626 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -422,8 +422,10 @@ public static String receive() { tokenMaxLimitMap.put(tokenNumberHash,tokenLimitForLevel); tokenDetailMap.put(tokenNumberHash, -1); tokenChain = new JSONArray("[" + wholeTokens.get(i).toString() + "]"); - - tokenHashStatus = Functions.checkTokenHash(tokenMaxLimitMap); + } + + if(wholeTokens.length() > 0) { + tokenHashStatus = Functions.checkTokenHash(tokenMaxLimitMap); } if(tokenHashStatus == false) { From e0abedf136ddac0b320d8de5ad4c5250653f3867 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Fri, 17 Jun 2022 13:58:09 +0530 Subject: [PATCH 172/179] Token Authentication and Dual commit - Bug fix --- src/com/rubix/Resources/Functions.java | 66 +++++----- .../rubix/TokenTransfer/TokenReceiver.java | 124 +++++++++--------- 2 files changed, 95 insertions(+), 95 deletions(-) diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index b2055dfd..8f74ec90 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -2133,44 +2133,38 @@ public static int readTokenHashTable(String path,String tokenContent) throws JSO } - public static boolean checkTokenHash(HashMap tokenDetailMap) throws InterruptedException { + public static HashMap checkTokenHash(HashMap tokenDetailMap, int tokenLimit) throws InterruptedException { HashMap tokenHashWithNumber = new HashMap<>(); - boolean status = true; - try { - long start = System.currentTimeMillis(); - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - int tokenLimit = Collections.max(tokenDetailMap.values()); - for(int i=1;i<= tokenLimit;i++) { - String tokenHashStr = calculateSHA256Hash(digest, String.valueOf(i)); - for(String tokenHash : tokenDetailMap.keySet()) { - if(tokenHash.equals(tokenHashStr)) { - - if(i > tokenDetailMap.get(tokenHash)) { - FunctionsLogger.debug("Invalid TokenHash"+tokenHash); - status = false; - break; - } - tokenHashWithNumber.put(tokenHash, i); - FunctionsLogger.debug("TokenHash is "+ tokenHash + " and token number is "+i); - }else { - FunctionsLogger.debug("Invalid TokenHash"+tokenHash); - status = false; - break; - } - - } - } - - FunctionsLogger.debug("final tokenHashMap is "+tokenHashWithNumber.toString()); - - - }catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - }catch (Exception e) { - e.printStackTrace(); - } - return status; + int tokenNumber = -1; + try { + long start = System.currentTimeMillis(); + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + + int flag = -1; + for(int i=1;i<=tokenLimit;i++) { + String tokenHashStr = calculateSHA256Hash(digest, String.valueOf(i)); + for(String tokenHash : tokenDetailMap.keySet()) { + if(tokenHash.equals(tokenHashStr)) { + tokenNumber = i; + flag++; + tokenHashWithNumber.put(tokenHash, i); + FunctionsLogger.debug("TokenHash is "+ tokenHash + " and token number is "+i); + } + + } + } + + FunctionsLogger.debug("final tokenHashMap is "+tokenHashWithNumber.toString()); + + + }catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + }catch (Exception e) { + e.printStackTrace(); + } + + return tokenHashWithNumber; } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 50f5f626..0ae713be 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -13,7 +13,12 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.Iterator; import java.util.Random; @@ -378,6 +383,58 @@ public static String receive() { allTokensChains.put(partTokenChainContent.get(i)); JSONArray invalidTokens = new JSONArray(); + + + /** Token Authenticity Check - starts */ + HashMap tokenMaxLimitMap= new HashMap<>(); + HashMap tokenDetailMap = new HashMap<>(); + + for(int i=0;itokenMaxLimitMap.get(tokenContent)) { + if(tokenDetailMap.get(tokenContent).equals(null)) { + TokenReceiverLogger.debug("Invalid Content Found in Token"); + String errorMessage = "Invalid Content Found in Token"; + output.println("426"); + 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(); + } + output.println("426"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + String errorMessage1 = "Token Number is greater than Token Limit for the Level"; + APIResponse.put("message", errorMessage1); + TokenReceiverLogger.debug(errorMessage1); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + } + /** Token Authenticity Check - Ends */ for (int count = 0; count < wholeTokens.length(); count++) { String tokens = null; @@ -409,42 +466,7 @@ public static String receive() { } } - /** Token Authenticity Check - starts */ - HashMap tokenMaxLimitMap= new HashMap<>(); - boolean tokenHashStatus = true; - - for(int i=0;i 0) { - tokenHashStatus = Functions.checkTokenHash(tokenMaxLimitMap); - } - - if(tokenHashStatus == false) { - TokenReceiverLogger.debug("Invalid Token!"); - String errorMessage = "Invalid Token!"; - output.println("426"); - 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(); - } - /** Token Authenticity Check - Ends */ + // ! check quorum signs for previous transaction for the tokenchain to verify // ! the ownership of sender for the token @@ -888,18 +910,10 @@ public static String receive() { int count = 0; for (int i = 0; i < intPart; i++) { - File tokenFile = new File(TOKENS_PATH.concat(wholeTokens.getString(i))); - TokenReceiverLogger.debug(wholeTokens.getString(i)+" file is exist : "+ tokenFile.exists()); - TokenReceiverLogger.debug(tokenFile.exists()); - if (!tokenFile.exists()) - tokenFile.createNewFile(); - - FileWriter fw = new FileWriter(tokenFile); - fw.write(wholeTokenContent.get(i)); - fw.flush(); - fw.close(); - add(TOKENS_PATH + wholeTokens.getString(i), ipfs); - pin(wholeTokens.getString(i), ipfs); + Path path = Paths.get(TOKENS_PATH + wholeTokens.get(i)); + Files.write(path, wholeTokenContent.get(i).getBytes()); + add(TOKENS_PATH + wholeTokens.get(i), ipfs); + pin(wholeTokens.get(i).toString(), ipfs); count++; } @@ -982,19 +996,11 @@ public static String receive() { obj2.put("owner", ownerIdentityHash); arr1.put(obj2); - File tokenFile = new File(TOKENS_PATH.concat(wholeTokens.getString(i))); - TokenReceiverLogger.debug(wholeTokens.getString(i)+" file is exist : "+ tokenFile.exists()); - TokenReceiverLogger.debug(tokenFile.exists()); - if (!tokenFile.exists()) - tokenFile.createNewFile(); - - FileWriter fw = new FileWriter(tokenFile); - fw.write(wholeTokenContent.get(i)); - fw.flush(); - fw.close(); + Path path = Paths.get(TOKENS_PATH + wholeTokens.get(i)); + Files.write(path, wholeTokenContent.get(i).getBytes()); writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); - TokenReceiverLogger.debug(wholeTokens.getString(i)+" file is exist : "+ tokenFile.exists()); + TokenReceiverLogger.debug(path+" file is exist : "+ Files.exists(path)); } From 7ed00057048c6c8afda6df0d5f7b57c519db818e Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Tue, 21 Jun 2022 16:06:32 +0530 Subject: [PATCH 173/179] Tokens file writing - Bug fix --- src/com/rubix/TokenTransfer/TokenReceiver.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 0ae713be..6ef8aeff 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -910,8 +910,8 @@ public static String receive() { int count = 0; for (int i = 0; i < intPart; i++) { - Path path = Paths.get(TOKENS_PATH + wholeTokens.get(i)); - Files.write(path, wholeTokenContent.get(i).getBytes()); + Path tokensPath = Paths.get(TOKENS_PATH + wholeTokens.get(i)); + Files.write(tokensPath, wholeTokenContent.get(i).getBytes()); add(TOKENS_PATH + wholeTokens.get(i), ipfs); pin(wholeTokens.get(i).toString(), ipfs); count++; @@ -996,11 +996,8 @@ public static String receive() { obj2.put("owner", ownerIdentityHash); arr1.put(obj2); - Path path = Paths.get(TOKENS_PATH + wholeTokens.get(i)); - Files.write(path, wholeTokenContent.get(i).getBytes()); - - writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); - TokenReceiverLogger.debug(path+" file is exist : "+ Files.exists(path)); + writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); + } @@ -1108,7 +1105,8 @@ public static String receive() { tokenObject1.put("tokenHash", wholeTokens.getString(i)); bankArray.put(tokenObject1); Functions.writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankArray.toString(), false); - + Path tokensPath = Paths.get(TOKENS_PATH + wholeTokens.get(i)); + Files.write(tokensPath, wholeTokenContent.get(i).getBytes()); } String partsFile = readFile(PAYMENTS_PATH.concat("PartsToken.json")); From aa4d369c445c8297586052dc0258052a4cb68000 Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Tue, 21 Jun 2022 21:25:52 +0530 Subject: [PATCH 174/179] Included Multiple Pin check, Sender and Receiver check in Quorum list --- .../rubix/TokenTransfer/TokenReceiver.java | 92 +-- src/com/rubix/TokenTransfer/TokenSender.java | 672 +++++++++--------- 2 files changed, 371 insertions(+), 393 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 6ef8aeff..04c8c5a2 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -401,76 +401,58 @@ public static String receive() { tokenDetailMap = Functions.checkTokenHash(tokenDetailMap,(int) Collections.max(tokenMaxLimitMap.values())); for(String tokenContent : tokenMaxLimitMap.keySet()) { - - if(tokenDetailMap.get(tokenContent)>tokenMaxLimitMap.get(tokenContent)) { - if(tokenDetailMap.get(tokenContent).equals(null)) { - TokenReceiverLogger.debug("Invalid Content Found in Token"); - String errorMessage = "Invalid Content Found in Token"; - output.println("426"); - 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(); - } - output.println("426"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - String errorMessage1 = "Token Number is greater than Token Limit for the Level"; - APIResponse.put("message", errorMessage1); - TokenReceiverLogger.debug(errorMessage1); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - } + if(tokenDetailMap.get(tokenContent).equals(null)) { + TokenReceiverLogger.debug("Invalid Content Found in Token"); + String errorMessage = "Invalid Content Found in Token"; + output.println("426"); + 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(); + } + if(tokenDetailMap.get(tokenContent)>tokenMaxLimitMap.get(tokenContent)) { + + output.println("426"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + String errorMessage1 = "Token Number is greater than Token Limit for the Level"; + APIResponse.put("message", errorMessage1); + TokenReceiverLogger.debug(errorMessage1); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + } /** Token Authenticity Check - Ends */ for (int count = 0; count < wholeTokens.length(); count++) { String tokens = null; - TokenReceiverLogger.debug("wholeTokens is " + wholeTokens.get(count).toString()); JSONArray tokenChain = new JSONArray("[" + wholeTokens.get(count).toString() + "]"); - TokenReceiverLogger.debug("tokenChain is " + tokenChain); - String TokenContent = get(wholeTokens.getString(count), ipfs); - TokenReceiverLogger.debug("TokenContent is " + TokenContent); - String tokenLevel = TokenContent.substring(0, TokenContent.length() - 64); - TokenReceiverLogger.debug("tokenLevel is " + tokenLevel); - String tokenNumberHash = TokenContent.substring(TokenContent.length() - 64); - TokenReceiverLogger.debug("tokenNumberHash is " + tokenNumberHash); - - // String tokenLevel = TokenContent.substring(0, 3); - // String tokenNumberHash = TokenContent.substring(3, - // TokenContent.indexOf("\n")); + String tokenContent = get(wholeTokens.getString(count), ipfs); + String tokenLevel = tokenContent.substring(0, tokenContent.length() - 64); + String tokenNumberHash = tokenContent.substring(tokenContent.length() - 64); int tokenLevelInt = Integer.parseInt(tokenLevel); int tokenLimitForLevel = tokenLimit[tokenLevelInt]; int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); int minumumStakeHeight = tokenLevelValue * 4; - int tokenNumber = -1; - - // check TokenHashTable exists - File tokenHashTable = new File(DATA_PATH.concat("DataHash")); - if (!tokenHashTable.exists()) { - if(generateMultiLoopWithHashMap(tokenHashTable.toString())) { - TokenReceiverLogger.debug("Initating check"); - } - } // ! check quorum signs for previous transaction for the tokenchain to verify // ! the ownership of sender for the token - if((tokenNumber >= 1204400) && (tokenLevelInt >= 4)) { + if((tokenDetailMap.get(tokenNumberHash) >= 1204400) && (tokenLevelInt >= 4)) { JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); TokenReceiverLogger.debug("Last Object = " + lastObject); diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index 8e95a3d2..d5353e3f 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -386,74 +386,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception JSONArray alphaQuorum = new JSONArray(); JSONArray betaQuorum = new JSONArray(); - JSONArray gammaQuorum = new JSONArray(); - int alphaSize; - - ArrayList alphaPeersList; - ArrayList betaPeersList; - ArrayList gammaPeersList; - - String senderSign = getSignFromShares(pvt, authSenderByRecHash); - - JSONObject partTokenChainArrays = new JSONObject(); - for (int i = 0; i < partTokens.length(); i++) { - String chainContent = readFile(tokenChainPath.concat(partTokens.getString(i)).concat(".json")); - JSONArray chainArray = new JSONArray(chainContent); - JSONObject newLastObject = new JSONObject(); - if (chainArray.length() == 0) { - newLastObject.put("previousHash", ""); - - } else { - JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); - secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); - newLastObject.put("previousHash", - calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); - } - - Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); - - newLastObject.put("senderSign", senderSign); - newLastObject.put("sender", senderDidIpfsHash); - newLastObject.put("receiver", receiverDidIpfsHash); - newLastObject.put("comment", comment); - newLastObject.put("tid", tid); - newLastObject.put("nextHash", ""); - newLastObject.put("role", "Sender"); - newLastObject.put("amount", amount); - chainArray.put(newLastObject); - partTokenChainArrays.put(partTokens.getString(i), chainArray); - - } - - JSONObject tokenDetails = new JSONObject(); - tokenDetails.put("whole-tokens", wholeTokens); - tokenDetails.put("whole-tokenChains", wholeTokenChainHash); - tokenDetails.put("hashSender", partTokenChainHash); - tokenDetails.put("part-tokens", partTokens); - tokenDetails.put("part-tokenChains", partTokenChainArrays); - tokenDetails.put("sender", senderDidIpfsHash); - String doubleSpendString = tokenDetails.toString(); - - String doubleSpend = calculateHash(doubleSpendString, "SHA3-256"); - writeToFile(LOGGER_PATH + "doubleSpend", doubleSpend, false); - TokenSenderLogger.debug("********Double Spend Hash*********: " + doubleSpend); - IPFSNetwork.addHashOnly(LOGGER_PATH + "doubleSpend", ipfs); - deleteFile(LOGGER_PATH + "doubleSpend"); - - JSONObject tokenObject = new JSONObject(); - tokenObject.put("tokenDetails", tokenDetails); - tokenObject.put("previousSender", tokenPreviousSender); - tokenObject.put("positions", positionsArray); - tokenObject.put("amount", requestedAmount); - tokenObject.put("amountLedger", amountLedger); - - if(Functions.multiplePinCheck(senderDidIpfsHash, tokenObject, ipfs) == 420) { - APIResponse.put("message", "Multiple Owners Found. Kindly re-initiate transaction"); - return APIResponse; - }else { - TokenSenderLogger.debug("No Multiple Pins found, initating transcation"); - } - + JSONArray gammaQuorum = new JSONArray(); JSONArray quorumArray = new JSONArray(); switch (type) { case 1: { @@ -471,11 +404,11 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } case 2: { - quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); + quorumArray = new JSONArray(readFile(DATA_PATH + "quorumlist.json")); break; } case 3: { - quorumArray = detailsObject.getJSONArray("quorum"); + quorumArray = detailsObject.getJSONArray("quorum"); break; } default: { @@ -486,7 +419,13 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception } } - + int alphaSize; + + ArrayList alphaPeersList; + ArrayList betaPeersList; + ArrayList gammaPeersList; + + List quorumList = new ArrayList<>(); String errMessage = null; for (int i = 0; i < quorumArray.length(); i++) { @@ -511,12 +450,13 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception TokenSenderLogger.debug("Updated quorumlist is "+quorumArray.toString()); + //sanity check for Quorum - starts int alphaCheck = 0, betaCheck = 0, gammaCheck = 0; JSONArray sanityFailedQuorum = new JSONArray(); for (int i = 0; i < quorumArray.length(); i++) { String quorumPeerID = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", quorumArray.getString(i)); - boolean quorumSanityCheck = sanityCheck("Quorum", quorumPeerID, ipfs, port + 11); + boolean quorumSanityCheck = sanityCheck("Quorum",quorumPeerID, ipfs, port + 11); if (!quorumSanityCheck) { sanityFailedQuorum.put(quorumPeerID); @@ -538,7 +478,7 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception TokenSenderLogger.warn("Quorum: ".concat(message.concat(sanityMessage))); return APIResponse; } - + //sanity check for Quorum - Ends long startTime, endTime, totalTime; QuorumSwarmConnect(quorumArray, ipfs); @@ -669,13 +609,80 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("message", "Sender Data Not Available"); return APIResponse; + } + + String senderSign = getSignFromShares(pvt, authSenderByRecHash); + JSONObject senderDetails2Receiver = new JSONObject(); + senderDetails2Receiver.put("sign", senderSign); + senderDetails2Receiver.put("tid", tid); + senderDetails2Receiver.put("comment", comment); + + JSONObject partTokenChainArrays = new JSONObject(); + for (int i = 0; i < partTokens.length(); i++) { + String chainContent = readFile(tokenChainPath.concat(partTokens.getString(i)).concat(".json")); + JSONArray chainArray = new JSONArray(chainContent); + JSONObject newLastObject = new JSONObject(); + if (chainArray.length() == 0) { + newLastObject.put("previousHash", ""); + + } else { + JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); + secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); + newLastObject.put("previousHash", + calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + } + + Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); + + newLastObject.put("senderSign", senderSign); + newLastObject.put("sender", senderDidIpfsHash); + newLastObject.put("receiver", receiverDidIpfsHash); + newLastObject.put("comment", comment); + newLastObject.put("tid", tid); + newLastObject.put("nextHash", ""); + newLastObject.put("role", "Sender"); + newLastObject.put("amount", amount); + chainArray.put(newLastObject); + partTokenChainArrays.put(partTokens.getString(i), chainArray); + + } + + JSONObject tokenDetails = new JSONObject(); + tokenDetails.put("whole-tokens", wholeTokens); + tokenDetails.put("whole-tokenChains", wholeTokenChainHash); + tokenDetails.put("hashSender", partTokenChainHash); + tokenDetails.put("part-tokens", partTokens); + tokenDetails.put("part-tokenChains", partTokenChainArrays); + tokenDetails.put("sender", senderDidIpfsHash); + String doubleSpendString = tokenDetails.toString(); + + String doubleSpend = calculateHash(doubleSpendString, "SHA3-256"); + writeToFile(LOGGER_PATH + "doubleSpend", doubleSpend, false); + TokenSenderLogger.debug("********Double Spend Hash*********: " + doubleSpend); + IPFSNetwork.addHashOnly(LOGGER_PATH + "doubleSpend", ipfs); + deleteFile(LOGGER_PATH + "doubleSpend"); + + JSONObject tokenObject = new JSONObject(); + tokenObject.put("tokenDetails", tokenDetails); + tokenObject.put("previousSender", tokenPreviousSender); + tokenObject.put("positions", positionsArray); + tokenObject.put("amount", requestedAmount); + tokenObject.put("amountLedger", amountLedger); + + if(Functions.multiplePinCheck(senderDidIpfsHash, tokenObject, ipfs) == 420) { + APIResponse.put("message", "Multiple Owners Found. Kindly re-initiate transaction"); + return APIResponse; }else { - /** - * Sending Token Details to Receiver - * Receiver to authenticate Tokens (Double Spending, IPFS availability) - */ - output.println(tokenObject); + TokenSenderLogger.debug("No Multiple Pins found, initating transcation"); } + + + /** + * Sending Token Details to Receiver + * Receiver to authenticate Tokens (Double Spending, IPFS availability) + */ + output.println(tokenObject); + String tokenAuth; try { @@ -764,50 +771,46 @@ public static JSONObject Send(String data, IPFS ipfs, int port) throws Exception APIResponse.put("status", "Failed"); return APIResponse; } - else { - JSONObject dataObject = new JSONObject(); - dataObject.put("tid", tid); - dataObject.put("message", doubleSpendString); - dataObject.put("receiverDidIpfs", receiverDidIpfsHash); - dataObject.put("pvt", pvt); - dataObject.put("senderDidIpfs", senderDidIpfsHash); - dataObject.put("token", wholeTokens.toString()); - dataObject.put("alphaList", alphaPeersList); - dataObject.put("betaList", betaPeersList); - dataObject.put("gammaList", gammaPeersList); - - InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 100, alphaSize, ""); - - JSONObject senderDetails2Receiver = new JSONObject(); - senderDetails2Receiver.put("sign", senderSign); - senderDetails2Receiver.put("tid", tid); - senderDetails2Receiver.put("comment", comment); - - if (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { - TokenSenderLogger.debug("Consensus Failed"); - senderDetails2Receiver.put("status", "Consensus Failed"); - 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()); - + + TokenSenderLogger.debug("Token Auth Code: " + tokenAuth); + + JSONObject dataObject = new JSONObject(); + dataObject.put("tid", tid); + dataObject.put("message", doubleSpendString); + dataObject.put("receiverDidIpfs", receiverDidIpfsHash); + dataObject.put("pvt", pvt); + dataObject.put("senderDidIpfs", senderDidIpfsHash); + dataObject.put("token", wholeTokens.toString()); + dataObject.put("alphaList", alphaPeersList); + dataObject.put("betaList", betaPeersList); + dataObject.put("gammaList", gammaPeersList); + + InitiatorProcedure.consensusSetUp(dataObject.toString(), ipfs, SEND_PORT + 100, alphaSize, ""); + + if (InitiatorConsensus.quorumSignature.length() < (minQuorum(alphaSize) + 2 * minQuorum(7))) { + TokenSenderLogger.debug("Consensus Failed"); + senderDetails2Receiver.put("status", "Consensus Failed"); output.println(senderDetails2Receiver); - TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); - } + 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); + TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); String signatureAuth; try { @@ -859,10 +862,10 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { APIResponse.put("message", "Sender not authenticated"); return APIResponse; - }else { - TokenSenderLogger.debug("Unpinned Tokens"); - output.println("Unpinned"); } + TokenSenderLogger.debug("Unpinned Tokens"); + output.println("Unpinned"); + String confirmation; try { @@ -912,12 +915,12 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { return APIResponse; } - else { - TokenSenderLogger.debug("3"); - TokenSenderLogger.debug("Whole tokens: " + wholeTokens); - TokenSenderLogger.debug("Part tokens: " + partTokens); - output.println(InitiatorProcedure.essential); - } + + TokenSenderLogger.debug("3"); + TokenSenderLogger.debug("Whole tokens: " + wholeTokens); + TokenSenderLogger.debug("Part tokens: " + partTokens); + output.println(InitiatorProcedure.essential); + String respAuth; try { @@ -966,68 +969,112 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { APIResponse.put("message", "Receiver process not over"); TokenSenderLogger.info("Incomplete Transaction"); return APIResponse; - }else { + } - TokenSenderLogger.debug("Operation over"); - - for (int i = 0; i < wholeTokens.length(); i++) - unpin(String.valueOf(wholeTokens.get(i)), ipfs); - repo(ipfs); - - 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); - - - JSONObject transactionRecord = new JSONObject(); - transactionRecord.put("role", "Sender"); - transactionRecord.put("tokens", allTokens); - 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); - requestedAmount = formatAmount(requestedAmount); - transactionRecord.put("amount-spent", requestedAmount); - - JSONArray transactionHistoryEntry = new JSONArray(); - transactionHistoryEntry.put(transactionRecord); - - updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); - - for (int i = 0; i < wholeTokens.length(); i++) - Files.deleteIfExists(Paths.get(tokenPath + wholeTokens.get(i))); - - for (int i = 0; i < wholeTokens.length(); i++) { - Functions.updateJSON("remove", PAYMENTS_PATH.concat("BNK00.json"), wholeTokens.getString(i)); + TokenSenderLogger.debug("Operation over"); + + for (int i = 0; i < wholeTokens.length(); i++) + unpin(String.valueOf(wholeTokens.get(i)), ipfs); + repo(ipfs); + + 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); + + + JSONObject transactionRecord = new JSONObject(); + transactionRecord.put("role", "Sender"); + transactionRecord.put("tokens", allTokens); + 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); + requestedAmount = formatAmount(requestedAmount); + transactionRecord.put("amount-spent", requestedAmount); + + JSONArray transactionHistoryEntry = new JSONArray(); + transactionHistoryEntry.put(transactionRecord); + + updateJSON("add", WALLET_DATA_PATH + "TransactionHistory.json", transactionHistoryEntry.toString()); + + for (int i = 0; i < wholeTokens.length(); i++) { + deleteFile(TOKENS_PATH.concat(wholeTokens.getString(i))); + Functions.updateJSON("remove", PAYMENTS_PATH.concat("BNK00.json"), wholeTokens.getString(i)); + } + + if (newPart) { + TokenSenderLogger.debug("Updating files for new parts"); + JSONObject newPartTokenObject = new JSONObject(); + newPartTokenObject.put("tokenHash", partTokens.getString(0)); + JSONArray newPartArray = new JSONArray(); + newPartArray.put(newPartTokenObject); + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), newPartArray.toString(), false); + + String bankNew = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bankNewArray = new JSONArray(bankNew); + bankNewArray.remove(0); + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankNewArray.toString(), false); + + String newTokenChain = readFile(TOKENCHAIN_PATH + partTokens.getString(0) + ".json"); + JSONArray chainArray = new JSONArray(newTokenChain); + + JSONObject newLastObject = new JSONObject(); + if (chainArray.length() == 0) { + newLastObject.put("previousHash", ""); + + } else { + JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); + secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); + newLastObject.put("previousHash", + calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + } + + Double amount = formatAmount(decimalAmount); + + newLastObject.put("senderSign", senderSign); + newLastObject.put("sender", senderDidIpfsHash); + newLastObject.put("receiver", receiverDidIpfsHash); + newLastObject.put("comment", comment); + newLastObject.put("tid", tid); + newLastObject.put("nextHash", ""); + newLastObject.put("role", "Sender"); + newLastObject.put("amount", amount); + chainArray.put(newLastObject); + writeToFile(TOKENCHAIN_PATH + partTokens.getString(0) + ".json", chainArray.toString(), false); + + File tokenFile = new File(TOKENS_PATH.concat(partTokens.getString(0))); + tokenFile.renameTo(new File(PART_TOKEN_PATH.concat(partTokens.getString(0)))); + File chainFile = new File(TOKENCHAIN_PATH.concat(partTokens.getString(0)).concat(".json")); + chainFile.renameTo(new File(PART_TOKEN_CHAIN_PATH.concat(partTokens.getString(0)).concat(".json"))); + + File shiftedFile = new File(PAYMENTS_PATH.concat("ShiftedTokens.json")); + if (!shiftedFile.exists()) { + shiftedFile.createNewFile(); + JSONArray shiftedTokensArray = new JSONArray(); + shiftedTokensArray.put(partTokens.getString(0)); + writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedTokensArray.toString(), false); + } else { + String shiftedContent = readFile(PAYMENTS_PATH.concat("ShiftedTokens.json")); + JSONArray shiftedArray = new JSONArray(shiftedContent); + shiftedArray.put(partTokens.getString(0)); + writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedArray.toString(), false); } - - - if (newPart) { - TokenSenderLogger.debug("Updating files for new parts"); - JSONObject newPartTokenObject = new JSONObject(); - newPartTokenObject.put("tokenHash", partTokens.getString(0)); - JSONArray newPartArray = new JSONArray(); - newPartArray.put(newPartTokenObject); - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), newPartArray.toString(), false); - - String bankNew = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray bankNewArray = new JSONArray(bankNew); - bankNewArray.remove(0); - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bankNewArray.toString(), false); - - String newTokenChain = readFile(TOKENCHAIN_PATH + partTokens.getString(0) + ".json"); + } else { + TokenSenderLogger.debug("Updating files for old parts"); + for (int i = 0; i < partTokens.length(); i++) { + String newTokenChain = readFile(TOKENCHAIN_PATH.concat("PARTS/") + partTokens.getString(i) + ".json"); JSONArray chainArray = new JSONArray(newTokenChain); JSONObject newLastObject = new JSONObject(); @@ -1037,11 +1084,13 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { } else { JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); - newLastObject.put("previousHash", - calculateHash(chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); + newLastObject.put("previousHash", calculateHash( + chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); } - Double amount = formatAmount(decimalAmount); + TokenSenderLogger + .debug("Amount from ledger: " + formatAmount(amountLedger.getDouble(partTokens.getString(i)))); + Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); newLastObject.put("senderSign", senderSign); newLastObject.put("sender", senderDidIpfsHash); @@ -1052,160 +1101,107 @@ else if (signatureAuth != null && (!signatureAuth.equals("200"))) { newLastObject.put("role", "Sender"); newLastObject.put("amount", amount); chainArray.put(newLastObject); - writeToFile(TOKENCHAIN_PATH + partTokens.getString(0) + ".json", chainArray.toString(), false); - - File tokenFile = new File(TOKENS_PATH.concat(partTokens.getString(0))); - tokenFile.renameTo(new File(PART_TOKEN_PATH.concat(partTokens.getString(0)))); - File chainFile = new File(TOKENCHAIN_PATH.concat(partTokens.getString(0)).concat(".json")); - chainFile.renameTo(new File(PART_TOKEN_CHAIN_PATH.concat(partTokens.getString(0)).concat(".json"))); - - File shiftedFile = new File(PAYMENTS_PATH.concat("ShiftedTokens.json")); - if (!shiftedFile.exists()) { - shiftedFile.createNewFile(); - JSONArray shiftedTokensArray = new JSONArray(); - shiftedTokensArray.put(partTokens.getString(0)); - writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedTokensArray.toString(), false); - } else { - String shiftedContent = readFile(PAYMENTS_PATH.concat("ShiftedTokens.json")); - JSONArray shiftedArray = new JSONArray(shiftedContent); - shiftedArray.put(partTokens.getString(0)); - writeToFile(PAYMENTS_PATH.concat("ShiftedTokens.json"), shiftedArray.toString(), false); - } - } else { - TokenSenderLogger.debug("Updating files for old parts"); - for (int i = 0; i < partTokens.length(); i++) { - String newTokenChain = readFile(TOKENCHAIN_PATH.concat("PARTS/") + partTokens.getString(i) + ".json"); - JSONArray chainArray = new JSONArray(newTokenChain); - - JSONObject newLastObject = new JSONObject(); - if (chainArray.length() == 0) { - newLastObject.put("previousHash", ""); - - } else { - JSONObject secondLastObject = chainArray.getJSONObject(chainArray.length() - 1); - secondLastObject.put("nextHash", calculateHash(tid, "SHA3-256")); - newLastObject.put("previousHash", calculateHash( - chainArray.getJSONObject(chainArray.length() - 1).getString("tid"), "SHA3-256")); - } - - TokenSenderLogger - .debug("Amount from ledger: " + formatAmount(amountLedger.getDouble(partTokens.getString(i)))); - Double amount = formatAmount(amountLedger.getDouble(partTokens.getString(i))); - - newLastObject.put("senderSign", senderSign); - newLastObject.put("sender", senderDidIpfsHash); - newLastObject.put("receiver", receiverDidIpfsHash); - newLastObject.put("comment", comment); - newLastObject.put("tid", tid); - newLastObject.put("nextHash", ""); - newLastObject.put("role", "Sender"); - newLastObject.put("amount", amount); - chainArray.put(newLastObject); - writeToFile(TOKENCHAIN_PATH.concat("PARTS/").concat(partTokens.getString(i)).concat(".json"), - chainArray.toString(), false); - - TokenSenderLogger.debug("Checking Parts Token Balance ..."); - Double availableParts = partTokenBalance(partTokens.getString(i)); - TokenSenderLogger.debug("Available: " + availableParts); - if (availableParts >= 1.000 || availableParts <= 0.000) { - TokenSenderLogger.debug("Wholly Spent, Removing token from parts"); - String partFileContent2 = readFile(PAYMENTS_PATH.concat("PartsToken.json")); - JSONArray partContentArray2 = new JSONArray(partFileContent2); - for (int j = 0; j < partContentArray2.length(); j++) { - if (partContentArray2.getJSONObject(j).getString("tokenHash").equals(partTokens.getString(i))) - partContentArray2.remove(j); - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partContentArray2.toString(), false); - } - deleteFile(PART_TOKEN_PATH.concat(partTokens.getString(i))); + writeToFile(TOKENCHAIN_PATH.concat("PARTS/").concat(partTokens.getString(i)).concat(".json"), + chainArray.toString(), false); + + TokenSenderLogger.debug("Checking Parts Token Balance ..."); + Double availableParts = partTokenBalance(partTokens.getString(i)); + TokenSenderLogger.debug("Available: " + availableParts); + if (availableParts >= 1.000 || availableParts <= 0.000) { + TokenSenderLogger.debug("Wholly Spent, Removing token from parts"); + String partFileContent2 = readFile(PAYMENTS_PATH.concat("PartsToken.json")); + JSONArray partContentArray2 = new JSONArray(partFileContent2); + for (int j = 0; j < partContentArray2.length(); j++) { + if (partContentArray2.getJSONObject(j).getString("tokenHash").equals(partTokens.getString(i))) + partContentArray2.remove(j); + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partContentArray2.toString(), false); } + deleteFile(PART_TOKEN_PATH.concat(partTokens.getString(i))); } - if (oldNew) { - String token = partTokens.getString(partTokens.length() - 1); - String bnk = readFile(PAYMENTS_PATH.concat("BNK00.json")); - JSONArray bnkArray = new JSONArray(bnk); - for (int i = 0; i < bnkArray.length(); i++) { - if (bnkArray.getJSONObject(i).getString("tokenHash").equals(token)) - bnkArray.remove(i); - } - writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bnkArray.toString(), false); + } + if (oldNew) { + String token = partTokens.getString(partTokens.length() - 1); + String bnk = readFile(PAYMENTS_PATH.concat("BNK00.json")); + JSONArray bnkArray = new JSONArray(bnk); + for (int i = 0; i < bnkArray.length(); i++) { + if (bnkArray.getJSONObject(i).getString("tokenHash").equals(token)) + bnkArray.remove(i); + } + writeToFile(PAYMENTS_PATH.concat("BNK00.json"), bnkArray.toString(), false); - JSONArray pArray = new JSONArray(); - JSONObject pObject = new JSONObject(); - pObject.put("tokenHash", token); - pArray.put(pObject); - writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), pArray.toString(), false); + JSONArray pArray = new JSONArray(); + JSONObject pObject = new JSONObject(); + pObject.put("tokenHash", token); + pArray.put(pObject); + writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), pArray.toString(), false); - } } - TokenSenderLogger.info("Transaction Successful"); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); - updateQuorum(quorumArray, signedQuorumList, true, type); - output.close(); - input.close(); - senderSocket.close(); - senderMutex = false; - - - // Populating data to explorer - if (!EXPLORER_IP.contains("127.0.0.1")) { - - List tokenList = new ArrayList<>(); - for (int i = 0; i < allTokens.length(); i++) - tokenList.add(allTokens.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", requestedAmount); - 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.info("Transaction Successful"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + receiverPeerId); + updateQuorum(quorumArray, signedQuorumList, true, type); + output.close(); + input.close(); + senderSocket.close(); + senderMutex = false; + - TokenSenderLogger.debug(response.toString()); + // Populating data to explorer + if (!EXPLORER_IP.contains("127.0.0.1")) { + + List tokenList = new ArrayList<>(); + for (int i = 0; i < allTokens.length(); i++) + tokenList.add(allTokens.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", requestedAmount); + 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(); - return APIResponse; - + TokenSenderLogger.debug(response.toString()); } + return APIResponse; } } From 02f958384700962976f331c6252af761c61a7d8d Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Thu, 23 Jun 2022 13:34:36 +0530 Subject: [PATCH 175/179] Token Authentication - Bug Fix --- .../rubix/TokenTransfer/TokenReceiver.java | 162 ++++++++++-------- 1 file changed, 88 insertions(+), 74 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 04c8c5a2..39af10e8 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -276,29 +276,94 @@ public static String receive() { int ipfsGetFlag = 0; ArrayList wholeTokenContent = new ArrayList<>(); ArrayList wholeTokenChainContent = new ArrayList<>(); - for (int i = 0; i < intPart; i++) { - String TokenChainContent = get(wholeTokenChains.getString(i), ipfs); - wholeTokenChainContent.add(TokenChainContent); - String TokenContent = get(wholeTokens.getString(i), ipfs); - wholeTokenContent.add(TokenContent); + + /** Token Authenticity Check - starts */ + HashMap tokenMaxLimitMap= new HashMap<>(); + HashMap tokenDetailMap = new HashMap<>(); + + for(int i=0;i 0) { + + if (!(ipfsGetFlag == intPart)) { + output.println("422"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + 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(); + ss.close(); + return APIResponse.toString(); + } + + int tokenMaxValue = Collections.max(tokenMaxLimitMap.values()); + TokenReceiverLogger.debug("Token Max Value : "+tokenMaxValue); + tokenDetailMap = Functions.checkTokenHash(tokenDetailMap,tokenMaxValue ); + + + if(tokenDetailMap.isEmpty()) { + TokenReceiverLogger.debug("Invalid Content Found in Token"); + String errorMessage = "Invalid Content Found in Token"; + output.println("426"); + 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 { + for(String tokenContent : tokenDetailMap.keySet()) { + TokenReceiverLogger.debug(tokenContent); + TokenReceiverLogger.debug(tokenDetailMap.get(tokenContent)); + TokenReceiverLogger.debug(tokenMaxLimitMap.get(tokenContent)); + + + if(tokenDetailMap.get(tokenContent) != null && tokenDetailMap.get(tokenContent) > tokenMaxLimitMap.get(tokenContent)) { + + output.println("426"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + String errorMessage1 = "Token Number is greater than Token Limit for the Level"; + APIResponse.put("message", errorMessage1); + TokenReceiverLogger.debug(errorMessage1); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } + } + } + + + } + /** Token Authenticity Check - Ends */ JSONArray partTokenChainContent = new JSONArray(); JSONArray partTokenContent = new JSONArray(); @@ -306,7 +371,7 @@ public static String receive() { for (int i = 0; i < partTokenChains.length(); i++) { partTokenChainContent.put(partTokenChains.getJSONArray(partTokens.getString(i))); - String TokenContent = get(partTokens.getString(i), ipfs); + String TokenContent = get(partTokens.getString(i), ipfs).trim(); partTokenContent.put(TokenContent); } @@ -385,61 +450,10 @@ public static String receive() { JSONArray invalidTokens = new JSONArray(); - /** Token Authenticity Check - starts */ - HashMap tokenMaxLimitMap= new HashMap<>(); - HashMap tokenDetailMap = new HashMap<>(); - - for(int i=0;itokenMaxLimitMap.get(tokenContent)) { - - output.println("426"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - String errorMessage1 = "Token Number is greater than Token Limit for the Level"; - APIResponse.put("message", errorMessage1); - TokenReceiverLogger.debug(errorMessage1); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } - } - /** Token Authenticity Check - Ends */ - for (int count = 0; count < wholeTokens.length(); count++) { String tokens = null; JSONArray tokenChain = new JSONArray("[" + wholeTokens.get(count).toString() + "]"); - String tokenContent = get(wholeTokens.getString(count), ipfs); + String tokenContent = get(wholeTokens.getString(count), ipfs).trim(); String tokenLevel = tokenContent.substring(0, tokenContent.length() - 64); String tokenNumberHash = tokenContent.substring(tokenContent.length() - 64); From e4c781bc3ecc23f17dbb9b69a49ee2018603700b Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Mon, 27 Jun 2022 14:49:44 +0530 Subject: [PATCH 176/179] Mining Issue fix --- src/com/rubix/Consensus/InitiatorConsensus.java | 7 ++++++- src/com/rubix/Mining/ProofCredits.java | 1 + src/com/rubix/Ping/PingCheck.java | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/com/rubix/Consensus/InitiatorConsensus.java b/src/com/rubix/Consensus/InitiatorConsensus.java index c540fd1b..df816187 100644 --- a/src/com/rubix/Consensus/InitiatorConsensus.java +++ b/src/com/rubix/Consensus/InitiatorConsensus.java @@ -43,7 +43,7 @@ public class InitiatorConsensus { public static ArrayList quorumWithShares = new ArrayList<>(); public static volatile int[] quorumResponse = { 0, 0, 0 }; public static volatile JSONArray finalQuorumSignsArray = new JSONArray(); - private static int socketTimeOut = 120000; + private static int socketTimeOut = 0; /** * This method increments the quorumResponse variable @@ -203,6 +203,11 @@ public static JSONObject start(String data, IPFS ipfs, int PORT, int index, Stri if (quorumResponse[index] <= minQuorum(quorumSize) && voteStatus) { InitiatorConsensusLogger.debug( "waiting for " + quorumSize + " +signs " + role); + if (role.equals("alpha")) { + InitiatorConsensusLogger + .debug("Picking Quorum for Staking " + quorumID[j]); + signedAphaQuorumArray.put(quorumID[j]); + } while (quorumResponse[index] < minQuorum(quorumSize)) { } InitiatorConsensusLogger.debug("between Q1- to Q" + quorumSize diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 1f013629..6c87bc1a 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -375,6 +375,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON APIResponse.put("status", "Failed"); APIResponse.put("message", "Consensus failed"); ProofCreditsLogger.debug("consensus failed"); + return APIResponse; } else { ProofCreditsLogger.debug("token mined " + token); diff --git a/src/com/rubix/Ping/PingCheck.java b/src/com/rubix/Ping/PingCheck.java index d7a25b67..e4387711 100644 --- a/src/com/rubix/Ping/PingCheck.java +++ b/src/com/rubix/Ping/PingCheck.java @@ -60,7 +60,7 @@ public static JSONObject Ping(String peerID, int port) throws IOException, JSONE forward(appName, port, peerID); PingSenderLogger.debug("Forwarded to " + appName + " on " + port); Socket senderSocket = new Socket("127.0.0.1", port); - senderSocket.setSoTimeout(socketTimeOut); + senderSocket.setSoTimeout(0); BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); PrintStream output = new PrintStream(senderSocket.getOutputStream()); From 0b5c972fda96df4526f0f63f39c3b10b274886b6 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Tue, 28 Jun 2022 16:55:34 +0530 Subject: [PATCH 177/179] Updated TokenReceiver to fix Exception --- src/com/rubix/Consensus/StakeConsensus.java | 4 +- src/com/rubix/Mining/ProofCredits.java | 20 ++- .../rubix/TokenTransfer/TokenReceiver.java | 164 +++++++++--------- 3 files changed, 101 insertions(+), 87 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index ccc5084b..026dc4b4 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -97,7 +97,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject String stakerDID = getValues(DATA_PATH + "DataTable.json", "didHash", "peerid", quorumPID[j]); - + StakeConsensusLogger.debug("stakerDID is " + stakerDID); StakeConsensusLogger.debug("Mined Token Details sent for validation...Staker DID is : " + stakerDID); @@ -242,7 +242,7 @@ public static void getStakeConsensus(JSONArray signedAphaQuorumArray, JSONObject // qOut[j].println("200"); StakeConsensusLogger.debug( "Staking completed for Peer: " + quorumPID[j]); - stakedDIDs.add(STAKED_QUORUM_DID); + stakedDIDs.add(quorumDID); stakeDetails.put(mineSigns); STAKE_SUCCESS++; }else { diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index 6c87bc1a..a61e7d3c 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -72,6 +72,7 @@ public class ProofCredits { private static int alphaSize = 0; public static String hashChainProof = new String(); + public static JSONObject create(String data, IPFS ipfs) throws IOException, JSONException { StakeConsensus.STAKE_SUCCESS = 0; @@ -95,6 +96,10 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON JSONArray alphaQuorum = new JSONArray(); JSONArray betaQuorum = new JSONArray(); JSONArray gammaQuorum = new JSONArray(); + JSONArray qstArray = new JSONArray(); + + boolean Status = false; + int creditsRequired = 50000, level; long starttime = System.currentTimeMillis(); @@ -312,11 +317,12 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } JSONArray signedQuorumList = new JSONArray(); - if (!oldCreditsFlag) { + boolean creditRemoveStatus = false; + if (!oldCreditsFlag) { ProofCreditsLogger.debug("New Credits"); // Send QST for verification String qstContent = readFile(WALLET_DATA_PATH.concat("QuorumSignedTransactions.json")); - JSONArray qstArray = new JSONArray(qstContent); + qstArray = new JSONArray(qstContent); int count = 0; JSONArray creditSignsArray = new JSONArray(); @@ -389,9 +395,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON } } - for (int i = 0; i < creditUsed; i++) - deleteFile(WALLET_DATA_PATH.concat("/Credits/") - .concat(qstArray.getJSONObject(i).getString("credits")).concat(".json")); + creditRemoveStatus = true; } } else { @@ -621,6 +625,12 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON transactionRecord.put("Date", currentTime); transactionRecord.put("totalTime", totalTime); transactionRecord.put("comment", "minedtxn"); + + if(creditRemoveStatus == true) { + for (int i = 0; i < creditUsed; i++) + deleteFile(WALLET_DATA_PATH.concat("/Credits/") + .concat(qstArray.getJSONObject(i).getString("credits")).concat(".json")); + } JSONArray transactionHistoryEntry = new JSONArray(); transactionHistoryEntry.put(transactionRecord); diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 39af10e8..5d942e9a 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -276,31 +276,31 @@ public static String receive() { int ipfsGetFlag = 0; ArrayList wholeTokenContent = new ArrayList<>(); ArrayList wholeTokenChainContent = new ArrayList<>(); - + /** Token Authenticity Check - starts */ - HashMap tokenMaxLimitMap= new HashMap<>(); - HashMap tokenDetailMap = new HashMap<>(); + HashMap tokenMaxLimitMap = new HashMap<>(); + HashMap tokenDetailMap = new HashMap<>(); + + for (int i = 0; i < wholeTokens.length(); i++) { - for(int i=0;i 0) { - - if (!(ipfsGetFlag == intPart)) { + String tokenLevel = tokenContent.substring(0, tokenContent.length() - 64); + String tokenNumberHash = tokenContent.substring(tokenContent.length() - 64); + + int tokenLevelInt = Integer.parseInt(tokenLevel); + int tokenLimitForLevel = tokenLimit[tokenLevelInt]; + tokenMaxLimitMap.put(tokenNumberHash, tokenLimitForLevel); + tokenDetailMap.put(tokenNumberHash, -1); + } + repo(ipfs); + + if (wholeTokens.length() > 0) { + + if (!(ipfsGetFlag == intPart)) { output.println("422"); APIResponse.put("did", senderDidIpfsHash); APIResponse.put("tid", "null"); @@ -314,56 +314,54 @@ public static String receive() { ss.close(); return APIResponse.toString(); } - - int tokenMaxValue = Collections.max(tokenMaxLimitMap.values()); - TokenReceiverLogger.debug("Token Max Value : "+tokenMaxValue); - tokenDetailMap = Functions.checkTokenHash(tokenDetailMap,tokenMaxValue ); - - - if(tokenDetailMap.isEmpty()) { - TokenReceiverLogger.debug("Invalid Content Found in Token"); - String errorMessage = "Invalid Content Found in Token"; - output.println("426"); - 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 { - for(String tokenContent : tokenDetailMap.keySet()) { - TokenReceiverLogger.debug(tokenContent); - TokenReceiverLogger.debug(tokenDetailMap.get(tokenContent)); - TokenReceiverLogger.debug(tokenMaxLimitMap.get(tokenContent)); - - - if(tokenDetailMap.get(tokenContent) != null && tokenDetailMap.get(tokenContent) > tokenMaxLimitMap.get(tokenContent)) { - - output.println("426"); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - String errorMessage1 = "Token Number is greater than Token Limit for the Level"; - APIResponse.put("message", errorMessage1); - TokenReceiverLogger.debug(errorMessage1); - executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); - } + + int tokenMaxValue = Collections.max(tokenMaxLimitMap.values()); + TokenReceiverLogger.debug("Token Max Value : " + tokenMaxValue); + tokenDetailMap = Functions.checkTokenHash(tokenDetailMap, tokenMaxValue); + + if (tokenDetailMap.isEmpty()) { + TokenReceiverLogger.debug("Invalid Content Found in Token"); + String errorMessage = "Invalid Content Found in Token"; + output.println("426"); + 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 { + for (String tokenContent : tokenDetailMap.keySet()) { + TokenReceiverLogger.debug(tokenContent); + TokenReceiverLogger.debug(tokenDetailMap.get(tokenContent)); + TokenReceiverLogger.debug(tokenMaxLimitMap.get(tokenContent)); + + if (tokenDetailMap.get(tokenContent) != null + && tokenDetailMap.get(tokenContent) > tokenMaxLimitMap.get(tokenContent)) { + + output.println("426"); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + String errorMessage1 = "Token Number is greater than Token Limit for the Level"; + APIResponse.put("message", errorMessage1); + TokenReceiverLogger.debug(errorMessage1); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); + } } } - - - } - /** Token Authenticity Check - Ends */ + + } + /** Token Authenticity Check - Ends */ JSONArray partTokenChainContent = new JSONArray(); JSONArray partTokenContent = new JSONArray(); @@ -447,12 +445,19 @@ public static String receive() { for (int i = 0; i < partTokenChainContent.length(); i++) allTokensChains.put(partTokenChainContent.get(i)); - JSONArray invalidTokens = new JSONArray(); + TokenReceiverLogger.debug("allTokenChain is "+allTokensChains.toString()); + JSONArray invalidTokens = new JSONArray(); + for (int count = 0; count < wholeTokens.length(); count++) { String tokens = null; - JSONArray tokenChain = new JSONArray("[" + wholeTokens.get(count).toString() + "]"); + TokenReceiverLogger.debug("Json array tokenChain value is " + wholeTokens.get(count).toString()); + TokenReceiverLogger.debug("Json array allTokensChains value is " + allTokensChains.get(count).toString()); + JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); + TokenReceiverLogger.debug("tokenchain is " + tokenChain); + TokenReceiverLogger.debug("tokenchain size is " + tokenChain.length()); + String tokenContent = get(wholeTokens.getString(count), ipfs).trim(); String tokenLevel = tokenContent.substring(0, tokenContent.length() - 64); String tokenNumberHash = tokenContent.substring(tokenContent.length() - 64); @@ -461,12 +466,11 @@ public static String receive() { int tokenLimitForLevel = tokenLimit[tokenLevelInt]; int tokenLevelValue = (int) Math.pow(2, tokenLevelInt + 2); int minumumStakeHeight = tokenLevelValue * 4; - - + // ! check quorum signs for previous transaction for the tokenchain to verify // ! the ownership of sender for the token - if((tokenDetailMap.get(tokenNumberHash) >= 1204400) && (tokenLevelInt >= 4)) { + if ((tokenDetailMap.get(tokenNumberHash) >= 1204400) && (tokenLevelInt >= 4)) { JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); TokenReceiverLogger.debug("Last Object = " + lastObject); @@ -590,6 +594,7 @@ public static String receive() { detailsToVerify.put("did", stakerDIDTC[stakeCount]); detailsToVerify.put("hash", mineIDTC[stakeCount]); detailsToVerify.put("signature", mineIDSignTC[stakeCount]); + if (Authenticate.verifySignature(detailsToVerify.toString())) { boolean minedTokenStatus = true; @@ -623,7 +628,7 @@ public static String receive() { invalidTokens.put(tokens); } - TokenReceiverLogger.debug("Staking check (2) successful"); + TokenReceiverLogger.debug("Staking check (2) successful for count "+stakeCount); // } else { // TokenReceiverLogger.debug( // "Staking check (2) failed: Could not verify mine ID signature"); @@ -905,20 +910,20 @@ public static String receive() { if (pinDetails.equals("Unpinned")) { int count = 0; for (int i = 0; i < intPart; i++) { - + Path tokensPath = Paths.get(TOKENS_PATH + wholeTokens.get(i)); Files.write(tokensPath, wholeTokenContent.get(i).getBytes()); add(TOKENS_PATH + wholeTokens.get(i), ipfs); - pin(wholeTokens.get(i).toString(), ipfs); - count++; - + pin(wholeTokens.get(i).toString(), ipfs); + count++; + } for (int i = 0; i < partTokens.length(); i++) { File tokenFile = new File(PART_TOKEN_PATH + partTokens.getString(i)); if (!tokenFile.exists()) tokenFile.createNewFile(); - + writeToFile(PART_TOKEN_PATH + partTokens.getString(i), partTokenContent.getString(i), false); String tokenHash = add(PART_TOKEN_PATH + partTokens.getString(i), ipfs); pin(tokenHash, ipfs); @@ -991,9 +996,8 @@ public static String receive() { obj2.put("tid", tid); obj2.put("owner", ownerIdentityHash); arr1.put(obj2); - + writeToFile(TOKENCHAIN_PATH + wholeTokens.getString(i) + ".json", arr1.toString(), false); - } From 4bbe6f140637f91f04cdf2e6926e8c1b33416ab0 Mon Sep 17 00:00:00 2001 From: Gokul P S Date: Wed, 29 Jun 2022 17:52:17 +0530 Subject: [PATCH 178/179] Stake token checks --- src/com/rubix/TokenTransfer/TokenReceiver.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 5d942e9a..58a9e7ff 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -470,7 +470,7 @@ public static String receive() { // ! check quorum signs for previous transaction for the tokenchain to verify // ! the ownership of sender for the token - if ((tokenDetailMap.get(tokenNumberHash) >= 1204400) && (tokenLevelInt >= 4)) { + //if ((tokenDetailMap.get(tokenNumberHash) >= 1204400) && (tokenLevelInt >= 4)) { JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); TokenReceiverLogger.debug("Last Object = " + lastObject); @@ -563,7 +563,8 @@ public static String receive() { stakedTokenSignTC[2] = threeOfThreeStake.getString(MiningConstants.STAKED_TOKEN_SIGN); stakerDIDTC[2] = threeOfThreeStake.getString(MiningConstants.STAKED_QUORUM_DID); mineIDTC[2] = threeOfThreeStake.getString(MiningConstants.MINE_ID); - mineIDSignTC[2] = threeOfThreeStake.getString(MiningConstants.MINE_ID); + mineIDSignTC[2] = threeOfThreeStake.getString(MiningConstants.MINE_ID_SIGN); + TokenReceiverLogger.debug("mineIDTC length is "+mineIDTC.length); for (int stakeCount = 0; stakeCount < mineIDTC.length; stakeCount++) { @@ -589,17 +590,21 @@ public static String receive() { if (stakerDIDTC[stakeCount].equals(stakerDIDMineData) && stakedTokenTC[stakeCount].equals(stakedTokenMineData) && stakedTokenSignTC[stakeCount].equals(stakedTokenSignMineData)) { + + TokenReceiverLogger.debug("array n non array data are same"); JSONObject detailsToVerify = new JSONObject(); detailsToVerify.put("did", stakerDIDTC[stakeCount]); detailsToVerify.put("hash", mineIDTC[stakeCount]); detailsToVerify.put("signature", mineIDSignTC[stakeCount]); + TokenReceiverLogger.debug("detailsToVerify - "+detailsToVerify.toString()); if (Authenticate.verifySignature(detailsToVerify.toString())) { boolean minedTokenStatus = true; ArrayList ownersArray = IPFSNetwork .dhtOwnerCheck(stakedTokenTC[stakeCount]); + TokenReceiverLogger.debug("dht owner are "+ownersArray.toString()+" size is "+ownersArray.size()); for (int i = 0; i < ownersArray.size(); i++) { if (ownersArray.get(i).equals(stakerDIDTC[stakeCount])) { minedTokenStatus = false; @@ -722,7 +727,7 @@ public static String receive() { } } - } + //} if (!ownerCheck) { TokenReceiverLogger.debug("Ownership Check Failed"); From 0429a73650d44fcb6ea81e111bb32f6f31e0715b Mon Sep 17 00:00:00 2001 From: Anuradha K Date: Fri, 1 Jul 2022 17:24:02 +0530 Subject: [PATCH 179/179] changed 6 digit Mining rule to 7 digit --- src/com/rubix/Consensus/StakeConsensus.java | 2 +- src/com/rubix/Mining/ProofCredits.java | 3 +- .../rubix/TokenTransfer/TokenReceiver.java | 40 ++++++++++--------- 3 files changed, 25 insertions(+), 20 deletions(-) diff --git a/src/com/rubix/Consensus/StakeConsensus.java b/src/com/rubix/Consensus/StakeConsensus.java index 026dc4b4..9858464f 100644 --- a/src/com/rubix/Consensus/StakeConsensus.java +++ b/src/com/rubix/Consensus/StakeConsensus.java @@ -31,7 +31,7 @@ public class StakeConsensus { public static Logger StakeConsensusLogger = Logger.getLogger(StakeConsensus.class); - private static int socketTimeOut = 1800000; + private static int socketTimeOut = 0; public static volatile int STAKE_LOCKED = 0; public static volatile int STAKE_SUCCESS = 0; public static volatile int STAKE_FAILED = 0; diff --git a/src/com/rubix/Mining/ProofCredits.java b/src/com/rubix/Mining/ProofCredits.java index a61e7d3c..b42118be 100644 --- a/src/com/rubix/Mining/ProofCredits.java +++ b/src/com/rubix/Mining/ProofCredits.java @@ -71,6 +71,7 @@ public class ProofCredits { private static ArrayList gammaPeersList; private static int alphaSize = 0; public static String hashChainProof = new String(); + private static int hashChainRule = 7; public static JSONObject create(String data, IPFS ipfs) throws IOException, JSONException { @@ -540,7 +541,7 @@ public static JSONObject create(String data, IPFS ipfs) throws IOException, JSON temp.put("tokenHash", tokenHash); JSONArray tempArray = new JSONArray(); tempArray.put(temp); - hashChainProof = HashChain.hashChainCounter(tid, StakeConsensus.stakedDIDs, 6); + hashChainProof = HashChain.hashChainCounter(tid, StakeConsensus.stakedDIDs, hashChainRule); ProofCreditsLogger.debug("HashChainProof is "+hashChainProof+" transcation id is "+ tid); updateJSON("add", PAYMENTS_PATH + "BNK00.json", tempArray.toString()); } else { diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 58a9e7ff..4c3bf08b 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -453,7 +453,6 @@ public static String receive() { for (int count = 0; count < wholeTokens.length(); count++) { String tokens = null; TokenReceiverLogger.debug("Json array tokenChain value is " + wholeTokens.get(count).toString()); - TokenReceiverLogger.debug("Json array allTokensChains value is " + allTokensChains.get(count).toString()); JSONArray tokenChain = new JSONArray(allTokensChains.get(count).toString()); TokenReceiverLogger.debug("tokenchain is " + tokenChain); TokenReceiverLogger.debug("tokenchain size is " + tokenChain.length()); @@ -469,13 +468,18 @@ public static String receive() { // ! check quorum signs for previous transaction for the tokenchain to verify // ! the ownership of sender for the token - - //if ((tokenDetailMap.get(tokenNumberHash) >= 1204400) && (tokenLevelInt >= 4)) { - - JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); - TokenReceiverLogger.debug("Last Object = " + lastObject); - - if (lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN)) { + JSONObject lastObject = new JSONObject(); + + if (tokenChain.length() > 0 ) { + + lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); + + } + TokenReceiverLogger.debug("Last Object = " + lastObject.toString()); + + + if (tokenChain.length() > 0 && lastObject.has("owner") && !lastObject.has(MiningConstants.STAKED_TOKEN) && + ( (tokenLevelInt == 4 && (tokenDetailMap.get(tokenNumberHash) >= 1204400)) || (tokenLevelInt >= 5)) ) { TokenReceiverLogger.debug("Checking ownership"); String owner = lastObject.getString("owner"); @@ -650,7 +654,7 @@ public static String receive() { } } - if (lastObject.has(MiningConstants.STAKED_TOKEN)) { + else if (tokenChain.length() > 0 && lastObject.has(MiningConstants.STAKED_TOKEN)) { Boolean minedTokenStatus = true; @@ -726,8 +730,8 @@ public static String receive() { // } } - } - //} + + } if (!ownerCheck) { TokenReceiverLogger.debug("Ownership Check Failed"); @@ -913,14 +917,14 @@ public static String receive() { } if (pinDetails.equals("Unpinned")) { - int count = 0; + int pinCount = 0; for (int i = 0; i < intPart; i++) { Path tokensPath = Paths.get(TOKENS_PATH + wholeTokens.get(i)); Files.write(tokensPath, wholeTokenContent.get(i).getBytes()); add(TOKENS_PATH + wholeTokens.get(i), ipfs); pin(wholeTokens.get(i).toString(), ipfs); - count++; + pinCount++; } @@ -935,7 +939,7 @@ public static String receive() { } - if (count == intPart) { + if (pinCount == intPart) { TokenReceiverLogger.debug("Pinned All Tokens"); output.println("Successfully Pinned"); @@ -958,8 +962,8 @@ public static String receive() { } long endTime = System.currentTimeMillis(); for (int i = 0; i < intPart; i++) { - String tokens = wholeTokens.getString(i); - String hashString = tokens.concat(receiverDidIpfsHash); + String wholeToken = wholeTokens.getString(i); + String hashString = wholeToken.concat(receiverDidIpfsHash); String hashForPositions = calculateHash(hashString, "SHA3-256"); BufferedImage pvt = ImageIO @@ -1020,8 +1024,8 @@ public static String receive() { String chequeHash = IPFSNetwork.add(LOGGER_PATH.concat(partTokens.getString(i)), ipfs); deleteFile(LOGGER_PATH.concat(partTokens.getString(i))); - String tokens = partTokens.getString(i); - String hashString = tokens.concat(receiverDidIpfsHash); + String partsTokens = partTokens.getString(i); + String hashString = partsTokens.concat(receiverDidIpfsHash); String hashForPositions = calculateHash(hashString, "SHA3-256"); BufferedImage pvt = ImageIO .read(new File(DATA_PATH.concat(receiverDidIpfsHash).concat("/PrivateShare.png")));