diff --git a/src/com/rubix/Ping/PingReceive.java b/src/com/rubix/Ping/PingReceive.java index 43f28818..ef09aaa4 100644 --- a/src/com/rubix/Ping/PingReceive.java +++ b/src/com/rubix/Ping/PingReceive.java @@ -93,8 +93,7 @@ public static String receive(String userType,int port) throws JSONException { PingReceiverLogger.info(userType + " Pong Sent "+currentVersion); } - else - if(pingRequest.contains("Get-TokenChain-Height")) { + else if(pingRequest.contains("Get-TokenChain-Height")) { String tokenHash; try { tokenHash = input.readLine(); @@ -125,9 +124,43 @@ public static String receive(String userType,int port) throws JSONException { height = chainArray.length()-1; PingReceiverLogger.info("Chain height: " + height); } + output.println(height); } } + else if(pingRequest.contains("Get-TokenChain")){ + 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) { + JSONArray tokenChain; + 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"); + tokenChain = new JSONArray(); + } + else{ + String tokenChainFileContent = readFile(TOKENCHAIN_PATH.concat(tokenHash).concat(".json")); + tokenChain = new JSONArray(tokenChainFileContent); + } + output.println(tokenChain); + } + } else{ APIResponse.put("status", "Failed"); APIResponse.put("message", "Request Failed"); diff --git a/src/com/rubix/Ping/VerifyStakedToken.java b/src/com/rubix/Ping/VerifyStakedToken.java index bd599f54..8939e26c 100644 --- a/src/com/rubix/Ping/VerifyStakedToken.java +++ b/src/com/rubix/Ping/VerifyStakedToken.java @@ -18,6 +18,7 @@ import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -26,8 +27,9 @@ 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 JSONArray tokenChain; - public static boolean Contact(String pid, int port, String tokenHash, String tokenContent) + public static boolean Contact(String pid, int port, String tokenHash, String tokenContent, String pingMessage) throws IOException, JSONException { repo(ipfs); PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); @@ -42,78 +44,123 @@ public static boolean Contact(String pid, int port, String tokenHash, String tok BufferedReader input = new BufferedReader(new InputStreamReader(senderSocket.getInputStream())); PrintStream output = new PrintStream(senderSocket.getOutputStream()); - output.println("Get-TokenChain-Height"); - output.println(tokenHash); - 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; - } + output.println(pingMessage); + + if(pingMessage.equals("Get-TokenChain-Height")) { + output.println(tokenHash); + 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); - } + 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); + } - String tokenLevel = tokenContent.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); + String tokenLevel = tokenContent.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; + } + else{ + tokenChain = new JSONArray(); + output.println(tokenHash); + String tokenChainResponse; + try { + tokenChainResponse = input.readLine(); + } catch (SocketException e) { + PingSenderLogger.warn("Node " + pid + " is unable to Respond! - Token Chain Ping"); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pid); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Node " + pid + "is unable to respond! - Token Chain Ping"); + + return false; } - 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) { + + if (tokenChainResponse == null) { + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pid); + PingSenderLogger.info("TokenChain not received"); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "TokenChain not received"); + return false; + + } else { + tokenChain = new JSONArray(tokenChainResponse); + PingSenderLogger.info("TokenChain received from " + pid); + PingSenderLogger.info("TokenChain: " + tokenChainResponse); + executeIPFSCommands(" ipfs p2p close -t /p2p/" + pid); + output.close(); + input.close(); + senderSocket.close(); + APIResponse.put("status", "Success"); + APIResponse.put("message", "Tokenchain Received"); return true; } + } - } else - PingSenderLogger.debug("GET request not worked"); - - return height > requiredMinedTokenHeight; } } \ No newline at end of file diff --git a/src/com/rubix/Resources/APIHandler.java b/src/com/rubix/Resources/APIHandler.java index 9ec7ca36..8f6c144e 100644 --- a/src/com/rubix/Resources/APIHandler.java +++ b/src/com/rubix/Resources/APIHandler.java @@ -242,9 +242,38 @@ public static String networkInfo() throws IOException, JSONException { } rd.close(); - writeToFile(DATA_PATH + "DataTable.json", result.toString(), false); - if (syncFlag == 1) { + if(syncFlag ==1) + { + APILogger.debug("Network info synced to DataTable.json"); + } + + URL url2 = new URL(SYNC_IP + "/getPubKeyData"); + HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection(); + conn2.setRequestMethod("GET"); + StringBuilder result2 = new StringBuilder(); + BufferedReader rd2 = new BufferedReader(new InputStreamReader(conn2.getInputStream())); + String line2; + int syncFlag2 =0; + + while ((line2 = rd2.readLine()) != null) { + result2.append(line2); + syncFlag2=1; + } + rd2.close(); + + File dt_PubKey = new File(DATA_PATH + "DataTable_PublicKeys.json"); + if (!dt_PubKey.exists()) { + dt_PubKey.createNewFile(); + } + + writeToFile(DATA_PATH + "DataTable_PublicKeys.json", result2.toString(), false); + if(syncFlag ==1) + { + APILogger.debug("Network info synced to DataTable_PublicKeys.json"); + } + + if (syncFlag == 1 && syncFlag2==1) { jsonObject.put("message", "Synced Successfully!"); } else { jsonObject.put("message", "Not synced! Try again after sometime."); diff --git a/src/com/rubix/Resources/Functions.java b/src/com/rubix/Resources/Functions.java index bf9cdd2c..ebae118c 100644 --- a/src/com/rubix/Resources/Functions.java +++ b/src/com/rubix/Resources/Functions.java @@ -1235,43 +1235,7 @@ public static void correctPartToken() throws JSONException { } } - public static void tokenBank() throws JSONException { - pathSet(); - String bank = readFile(PAYMENTS_PATH.concat("BNK00.json")); - 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")); - } - - 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); - } - - 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())); - } - - } public static Double getPartsBalance() throws JSONException { pathSet(); @@ -1551,25 +1515,7 @@ public static void clearParts() throws JSONException { writeToFile(PAYMENTS_PATH.concat("PartsToken.json"), partsArray.toString(), false); } - public static void backgroundChecks() { - try { - Functions.tokenBank(); - } catch (JSONException e) { - e.printStackTrace(); - } - - try { - Functions.clearParts(); - } catch (JSONException e) { - e.printStackTrace(); - } - - IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); - IPFSNetwork.repo(ipfs); - - addPublicData(); - - } + public static String sanityMessage; diff --git a/src/com/rubix/TokenTransfer/ForkResolution.java b/src/com/rubix/TokenTransfer/ForkResolution.java index 1c2f3026..ed6b8f90 100644 --- a/src/com/rubix/TokenTransfer/ForkResolution.java +++ b/src/com/rubix/TokenTransfer/ForkResolution.java @@ -1,5 +1,6 @@ package com.rubix.TokenTransfer; +import com.rubix.Ping.VerifyStakedToken; import com.rubix.Resources.IPFSNetwork; import org.apache.log4j.Logger; import org.json.JSONArray; @@ -9,13 +10,15 @@ import java.io.IOException; import java.util.ArrayList; +import static com.rubix.Resources.Functions.*; + public class ForkResolution { public static Logger ForkResolutionLogger = Logger.getLogger(ForkResolution.class); public static String resolutionMessage; public static ArrayList pinOwnersArrayTransferToken = new ArrayList(); public static ArrayList pinOwnersArrayPledgedToken = new ArrayList(); + public static boolean check(JSONObject tokenDetails) throws IOException, InterruptedException, JSONException { - boolean resolution = true; /** * 1. Check number of pins on the token * 2. If number of pins < 2 - Pass the token @@ -24,9 +27,14 @@ public static boolean check(JSONObject tokenDetails) throws IOException, Interru * 5. Else reject the transfer token * 6. If number of pins on the pledged token == 1 - Pass the transfer token * 7. Else Reject the transfer token + * 8. Check if the transfer token is a recently unpledged token + * 9. If it is - Contact the node owning token [Ct] it pledged for and ask for the tokenchain height + * 10.Make sure Ct has genuine pins or match the height of the pledging */ - ForkResolutionLogger.debug("Token Details:" + tokenDetails); + boolean resolution = true; + +// ForkResolutionLogger.debug("Token Details:" + tokenDetails); ArrayList previousSender = new ArrayList(); JSONArray ownersReceived = new JSONArray(); @@ -35,60 +43,167 @@ public static boolean check(JSONObject tokenDetails) throws IOException, Interru String token = tokenDetails.getString("token"); JSONArray tokenChain = tokenDetails.getJSONArray("tokenChain"); - + ForkResolutionLogger.debug("Unpledged Token Check: " + token); boolean tokenOwners = true; - try { - ForkResolutionLogger.debug("Checking owners for " + token + " Please wait..."); - pinOwnersArrayTransferToken = IPFSNetwork.dhtOwnerCheck(token); + ForkResolutionLogger.debug("Checking owners for " + token + " Please wait..."); + pinOwnersArrayTransferToken = IPFSNetwork.dhtOwnerCheck(token); - if (pinOwnersArrayTransferToken.size() > 2) { - - for (int j = 0; j < previousSendersArray.length(); j++) { - if (previousSendersArray.getJSONObject(j).getString("token").equals(token)) - ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); - } + if (pinOwnersArrayTransferToken.size() > 2) { + ForkResolutionLogger.debug("Multiple pins found"); + for (int j = 0; j < previousSendersArray.length(); j++) { + if (previousSendersArray.getJSONObject(j).getString("token").equals(token)) + ownersReceived = previousSendersArray.getJSONObject(j).getJSONArray("sender"); + } - for (int j = 0; j < ownersReceived.length(); j++) { - previousSender.add(ownersReceived.getString(j)); - } + for (int j = 0; j < ownersReceived.length(); j++) { + previousSender.add(ownersReceived.getString(j)); + } - for (int j = 0; j < pinOwnersArrayTransferToken.size(); j++) { - if (!previousSender.contains(pinOwnersArrayTransferToken.get(j).toString())) - tokenOwners = false; + for (int j = 0; j < pinOwnersArrayTransferToken.size(); j++) { + if (!previousSender.contains(pinOwnersArrayTransferToken.get(j).toString())) { + ForkResolutionLogger.debug("Multiple pins of " + pinOwnersArrayTransferToken.get(j).toString() + " not contained in history"); + tokenOwners = false; + }else{ + ForkResolutionLogger.debug("Multiple pins of " + pinOwnersArrayTransferToken.get(j).toString() + " contained in history"); } } - else - ForkResolutionLogger.debug("Token " + token + " has not multiple pins. Passed !!!"); - } catch (IOException | InterruptedException e) { - ForkResolutionLogger.debug("Ipfs dht find did not execute"); - } + } else + ForkResolutionLogger.debug("Token " + token + " has not multiple pins. Passed !!!"); + if (!tokenOwners) { - JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); - ForkResolutionLogger.debug("Last Object of token " + token + ": " + lastObject); - if(lastObject.has("tokensPledgedWith")){ - if(lastObject.getJSONArray("tokensPledgedWith") != null) { - JSONArray pledgeTokens = lastObject.getJSONArray("tokensPledgedWith"); - for (int i = 0; i < pledgeTokens.length(); i++) { - ForkResolutionLogger.debug("Checking owners for pledgeToken" + pledgeTokens.getString(i) + " Please wait..."); - pinOwnersArrayPledgedToken = IPFSNetwork.dhtOwnerCheck(pledgeTokens.getString(i)); - if (pinOwnersArrayPledgedToken.size() != 1) { - resolution = false; - resolutionMessage = "Pledge token has more than one owner"; - } else { - ForkResolutionLogger.debug("Pledged Token " + pledgeTokens.getString(i) + " has not multiple pins. Passed !!!"); - return true; - } - } - } - } - else { - resolution = false; - resolutionMessage = "Transfer token has more owner and no token pledged for"; - } + ForkResolutionLogger.debug("Multiple pins found for token " + token + ". Checking for pledged details "); + + JSONObject lastObject = tokenChain.getJSONObject(tokenChain.length() - 1); +// ForkResolutionLogger.debug("Last Object of token " + token + ": " + lastObject); + if (lastObject.has("tokensPledgedWith")) { + if (lastObject.getJSONArray("tokensPledgedWith") != null) { + JSONArray pledgeTokens = lastObject.getJSONArray("tokensPledgedWith"); + ForkResolutionLogger.debug("pledgedTokens: " + pledgeTokens); + for (int i = 0; i < pledgeTokens.length(); i++) { + ForkResolutionLogger.debug("Checking owners for pledgeToken" + pledgeTokens.get(i).toString() + " Please wait..."); + pinOwnersArrayPledgedToken = IPFSNetwork.dhtOwnerCheck(pledgeTokens.get(i).toString()); + if (pinOwnersArrayPledgedToken.size() != 1) { + resolution = false; + resolutionMessage = "Pledge token has more than one owner"; + } else { + ForkResolutionLogger.debug("Pledged Token " + pledgeTokens.get(i).toString() + " has not multiple pins. Passed !!!"); + return true; + } + } + } + } else { + resolution = false; + resolutionMessage = "Transfer token has more owner and no token pledged for"; + } } return resolution; + + } + + public static boolean verifyUnpledgedToken(String transferToken, String pledgedToken) throws IOException, InterruptedException, JSONException { + ForkResolutionLogger.debug("Pledged Token Check: " + transferToken); + + ArrayList pinListTransferToken = IPFSNetwork.dhtOwnerCheck(transferToken); + if(pinListTransferToken.size() > 2) { + ForkResolutionLogger.debug("Transfer token " + transferToken + " has multiple pins. Checking pledged details"); + ArrayList pinListPledgeToken = IPFSNetwork.dhtOwnerCheck(pledgedToken); + if (pinListPledgeToken.size() > 1) { + ForkResolutionLogger.debug("Pledged token has multiple pins. Verifying token chain height details"); + JSONArray tokenChainsList = new JSONArray(); + for (int i = 0; i < pinListPledgeToken.size(); i++) { + boolean listStatus = VerifyStakedToken.Contact(pinListPledgeToken.get(i).toString(), SEND_PORT + 16, pledgedToken, "", "Get-TokenChain"); + if (listStatus) { + JSONObject chainObject = new JSONObject(); + chainObject.put("node", pinListPledgeToken.get(i).toString()); + chainObject.put("chain", VerifyStakedToken.tokenChain); + chainObject.put("hash", calculateHash(VerifyStakedToken.tokenChain.toString(), "SHA3-256")); + chainObject.put("length", VerifyStakedToken.tokenChain.length()); + + tokenChainsList.put(chainObject); + } else { + ForkResolutionLogger.debug("Node " + pinListPledgeToken.get(i).toString() + " have not responded with token chain"); + } + } + ForkResolutionLogger.debug("Token chain details from pinned nodes received"); + + /** + * Remove token chains that do not contain transfer token + */ + for (int i = 0; i < tokenChainsList.length(); i++) { + String chainString = tokenChainsList.getJSONObject(i).getJSONArray("chain").toString(); + if(!chainString.contains(transferToken)) + tokenChainsList.remove(i); + } + + ForkResolutionLogger.debug("Token chains to be iterated:"); + for (int i = 0; i < tokenChainsList.length(); i++) { + ForkResolutionLogger.debug(tokenChainsList.getJSONObject(i).getString("node")); + } + + /** + * Create hashes and verify remaining token chains + */ + + /** + * Iterate through chains until transfer token found in the object with correct receiver + */ + boolean includedCheck = true; + for (int i = 0; i < tokenChainsList.length(); i++) { + JSONArray chain = tokenChainsList.getJSONObject(i).getJSONArray("chain"); + includedCheck = true; + for (int j = chain.length() - 1; j > 0; j--) { + ForkResolutionLogger.debug("Object " + j); + JSONObject chainIndexObject = chain.getJSONObject(j); + if (chainIndexObject.has("tokensPledgedWith")) { + String tokensPledgedWithString = chainIndexObject.get("tokensPledgedWith").toString(); + ForkResolutionLogger.debug("tokensPledgedWithString: " + tokensPledgedWithString + " pledgedToken: " + pledgedToken); + if (tokensPledgedWithString.contains(transferToken)) { + ForkResolutionLogger.debug("tokensPledgedWithString.contains(pledgedToken)"); + String receiverPID = getValues(DATA_PATH.concat("DataTable.json"), "peerid", "didHash", chainIndexObject.getString("receiver")); + ForkResolutionLogger.debug("Receiver: " + receiverPID + " Node: " + tokenChainsList.getJSONObject(i).getString("node")); + if(receiverPID.equals(tokenChainsList.getJSONObject(i).getString("node"))) { + ForkResolutionLogger.debug("Receiver IDs match"); + if (j < chain.length() - 1) { + resolutionMessage = "<1> Token Pledged correctly in the appropriate level"; + ForkResolutionLogger.debug(" <1> Token Pledged correctly in the appropriate level"); + includedCheck = true; + } else { + resolutionMessage = "<2> Token Pledged maliciously. Present in the current level"; + ForkResolutionLogger.debug(" <2> Token Pledged maliciously. Present in the current level"); + includedCheck = false; + } + } else{ + resolutionMessage = "<3> Wrong pledge object"; + ForkResolutionLogger.debug("<3> Wrong pledge object"); + includedCheck = false; + } + } else { + resolutionMessage = " <4> Token Chain object does not contain the pledged token details"; + ForkResolutionLogger.debug(" <4> Token Chain object does not contain the pledged token details"); + includedCheck = false; + } + } else { + resolutionMessage = "<5> Token Chain Object does not have pledge details"; + ForkResolutionLogger.debug(" <5> Token Chain Object does not have pledge details"); + includedCheck = false; + } + } + ForkResolutionLogger.debug("Token " + transferToken + " was pledged for " + pledgedToken + " and check status for token chain of " + tokenChainsList.getJSONObject(i).getString("node") + " is " + includedCheck); + } + if (includedCheck) + return true; + ForkResolutionLogger.debug("Transfer token " + transferToken + " not found in any pledged token chains"); + return false; + } else { + ForkResolutionLogger.debug("Pledged token has no pins. Passed !!!"); + return true; + } + }else { + ForkResolutionLogger.debug("Transfer token " + transferToken + " has no multiple pins. Passed !!!"); + return true; + } } } diff --git a/src/com/rubix/TokenTransfer/TokenReceiver.java b/src/com/rubix/TokenTransfer/TokenReceiver.java index 1de3abab..d2583b19 100644 --- a/src/com/rubix/TokenTransfer/TokenReceiver.java +++ b/src/com/rubix/TokenTransfer/TokenReceiver.java @@ -193,6 +193,7 @@ public static String receive() { JSONObject partTokenChains = TokenDetails.getJSONObject("part-tokenChains"); JSONObject partTokenChainsForVerification = TokenDetails.getJSONObject("part-tokenChains-PrevState"); JSONArray partTokenChainsHash = TokenDetails.getJSONArray("hashSender"); + JSONObject distributedObject = TokenDetails.getJSONObject("distributedObject"); if (TokenDetails.optJSONArray("proof") != null) { JSONArray proofArray = TokenDetails.getJSONArray("proof"); @@ -330,38 +331,58 @@ public static String receive() { tokenDetailMap.put(tokenNumberHash, -1); } - boolean forkResolution = true; - TokenReceiverLogger.debug("Fork Checking version 3: "); - TokenReceiverLogger.debug("Whole Token Chains: " + wholeTokenChainContent.get(0)); - TokenReceiverLogger.debug("Whole Token Chains: " + new JSONArray(wholeTokenChainContent.get(0))); - JSONArray forkedTokens = new JSONArray(); - for (int i = 0; i < wholeTokens.length(); ++i) { - TokenReceiverLogger.debug("Fork Checking for token: " + wholeTokens.getString(i)); - JSONObject forkObject = new JSONObject(); - forkObject.put("token", wholeTokens.getString(i)); - forkObject.put("tokenChain", new JSONArray(wholeTokenChainContent.get(i))); - forkObject.put("previousSendersArray", previousSendersArray); - forkResolution = ForkResolution.check(forkObject); - if(!forkResolution) { - TokenReceiverLogger.debug("Fork found and not resolved for token: " + wholeTokens.getString(i)); - TokenReceiverLogger.debug("Message: " + ForkResolution.resolutionMessage); - forkedTokens.put(wholeTokens.getString(i)); + if(intPart > 0) { + + boolean forkResolution = true; + TokenReceiverLogger.debug("Fork Checking version 3: "); + TokenReceiverLogger.debug("Whole Token Chains: " + wholeTokenChainContent.get(0)); + TokenReceiverLogger.debug("Whole Token Chains: " + new JSONArray(wholeTokenChainContent.get(0))); + JSONArray forkedTokens = new JSONArray(); + for (int i = 0; i < wholeTokens.length(); ++i) { + TokenReceiverLogger.debug("Fork Checking for token: " + wholeTokens.getString(i)); + + JSONArray tokenChain = new JSONArray(wholeTokenChainContent.get(i)); + JSONObject forkObject = new JSONObject(); + forkObject.put("token", wholeTokens.getString(i)); + forkObject.put("tokenChain", tokenChain); + forkObject.put("previousSendersArray", previousSendersArray); + + + if(tokenChain.getJSONObject(tokenChain.length()-1).has("pledgeToken")){ + TokenReceiverLogger.debug("Token " + wholeTokens.getString(i) + " is a new token (SHAG structure)"); + if(!tokenChain.getJSONObject(tokenChain.length()-1).getString("pledgeToken").equals("")){ + TokenReceiverLogger.debug("Token " + wholeTokens.getString(i) + " is a pledged token"); + forkResolution = ForkResolution.verifyUnpledgedToken(wholeTokens.getString(i), tokenChain.getJSONObject(tokenChain.length()-1).getJSONArray("tokensPledgedFor").get(0).toString()); + + } else { + TokenReceiverLogger.debug("Token " + wholeTokens.getString(i) + " is a new token (SHAG structure) and not pledged"); + forkResolution = ForkResolution.check(forkObject); + } + }else { + TokenReceiverLogger.debug("Token " + wholeTokens.getString(i) + " is an Eismeer Token"); + forkResolution = ForkResolution.check(forkObject); + } + if(!forkResolution) { + TokenReceiverLogger.debug("Fork found and not resolved for token: " + wholeTokens.getString(i)); + TokenReceiverLogger.debug("Message: " + ForkResolution.resolutionMessage); + forkedTokens.put(wholeTokens.getString(i)); + } + } + if (!forkResolution) { + TokenReceiverLogger.debug("Fork not resolved for " + forkedTokens); + output.println("418"); + output.println(forkedTokens.toString()); + APIResponse.put("did", senderDidIpfsHash); + APIResponse.put("tid", "null"); + APIResponse.put("status", "Failed"); + APIResponse.put("message", "Fork not resolved"); + IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); + output.close(); + input.close(); + sk.close(); + ss.close(); + return APIResponse.toString(); } - } - if (!forkResolution) { - TokenReceiverLogger.debug("Fork not resolved for " + forkedTokens); - output.println("418"); - output.println(forkedTokens.toString()); - APIResponse.put("did", senderDidIpfsHash); - APIResponse.put("tid", "null"); - APIResponse.put("status", "Failed"); - APIResponse.put("message", "Fork not resolved"); - IPFSNetwork.executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPeerID); - output.close(); - input.close(); - sk.close(); - ss.close(); - return APIResponse.toString(); } //QmWcmK38g9XcrCwhoEq3rQjNseJW2HyscoG66DWF62X6bK.proof @@ -1328,7 +1349,7 @@ public static String receive() { 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"))) { + mineIDContentJSON.getString("tokenContent"), "Get-TokenChain-Height")) { minedTokenStatus = false; } } @@ -1683,6 +1704,7 @@ public static String receive() { lastObject.put("pledgeToken", ""); lastObject.put("tokensPledgedFor", allTokens); lastObject.put("tokensPledgedWith", pledgedDetails); + lastObject.put("distributedObject", distributedObject); if (!BlockHash.isEmpty()) { lastObject.put("blockHash", BlockHash); @@ -1809,6 +1831,10 @@ public static String receive() { newPartObject.put("receiver", receiverDidIpfsHash); newPartObject.put("comment", comment); newPartObject.put("tid", tid); + newPartObject.put("pledgeToken", ""); + newPartObject.put("tokensPledgedFor", allTokens); + newPartObject.put("tokensPledgedWith", pledgedDetails); + newPartObject.put("distributedObject", distributedObject); // newPartObject.put("nextHash", ""); // newPartObject.put("owner", ownerIdentityHash); /* diff --git a/src/com/rubix/TokenTransfer/TokenSender.java b/src/com/rubix/TokenTransfer/TokenSender.java index c597fd7e..867da5d1 100644 --- a/src/com/rubix/TokenTransfer/TokenSender.java +++ b/src/com/rubix/TokenTransfer/TokenSender.java @@ -541,7 +541,7 @@ public static JSONObject SendPartA(String data, IPFS ipfs, int port) throws Exce dataToSendToInitiator.put("sender", senderDidIpfsHash); dataToSendToInitiator.put("receiver", receiverDidIpfsHash); - TokenSenderLogger.debug("Details being sent to Initiator: " + dataToSendToInitiator); +// TokenSenderLogger.debug("Details being sent to Initiator: " + dataToSendToInitiator); boolean abort = Initiator.pledgeSetUp(dataToSendToInitiator.toString(), ipfs, 22143); if (abort) { @@ -581,7 +581,10 @@ public static JSONObject SendPartA(String data, IPFS ipfs, int port) throws Exce lastObject.put("receiver", receiverDidIpfsHash); lastObject.put("pledgeToken", ""); lastObject.put("tokensPledgedFor", allTokens); - lastObject.put("tokensPledgedWith", Initiator.pledgedTokensArray); + lastObject.put("tokensPledgedWith", Initiator.pledgedTokensWithNodesArray); + lastObject.put("distributedObject", Initiator.distributedObject); +// TokenSenderLogger.debug("Distributed Object in TokenSender: " + Initiator.distributedObject); + String tokenChainFileContent = readFile(TOKENCHAIN_PATH + wholeTokens.get(i) + ".json"); JSONArray tokenChain = new JSONArray(tokenChainFileContent); @@ -643,12 +646,12 @@ public static JSONObject SendPartA(String data, IPFS ipfs, int port) throws Exce return APIResponse; } - TokenSenderLogger.debug("pledge object is " + pledgeArray.toString()); +// TokenSenderLogger.debug("pledge object is " + pledgeArray.toString()); for (int i = 0; i < Initiator.quorumWithHashesArray.length(); i++) { JSONObject jsonObject = Initiator.quorumWithHashesArray.getJSONObject(i); Iterator keys = jsonObject.keys(); - TokenSenderLogger.debug("jsonObject is " + jsonObject.toString()); +// TokenSenderLogger.debug("jsonObject is " + jsonObject.toString()); JSONObject pledgeSignedObject = new JSONObject(); String key = ""; JSONArray hashAndSignsArray = new JSONArray(); @@ -659,7 +662,7 @@ public static JSONObject SendPartA(String data, IPFS ipfs, int port) throws Exce // do something with jsonObject here JSONArray hashArray = new JSONArray(jsonObject.get(key).toString()); - TokenSenderLogger.debug("@@@@@ Calculating hash for: " + hashArray); +// TokenSenderLogger.debug("@@@@@ Calculating hash for: " + hashArray); // String hashString = calculateHash(hashArray.toString(), "SHA3-256"); for (int j = 0; j < hashArray.length(); j++) { String sign = getSignFromShares(pvt, hashArray.get(j).toString()); @@ -671,7 +674,7 @@ public static JSONObject SendPartA(String data, IPFS ipfs, int port) throws Exce } JSONObject signObject = new JSONObject(); signObject.put(key, hashAndSignsArray); - TokenSenderLogger.debug("signObject is " + signObject); +// TokenSenderLogger.debug("signObject is " + signObject); quorumWithSignsArray.put(signObject); } @@ -707,7 +710,7 @@ public static JSONObject SendPartA(String data, IPFS ipfs, int port) throws Exce // } payloadSigned.put("pledgeDetails", quorumWithSignsArray); - TokenSenderLogger.debug("pledgeDetails: " + quorumWithSignsArray); +// TokenSenderLogger.debug("pledgeDetails: " + quorumWithSignsArray); FileWriter spfile = new FileWriter(WALLET_DATA_PATH.concat("/signedPayload").concat(tid).concat(".json")); spfile.write(payloadSigned.toString()); @@ -927,9 +930,10 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) tokenDetails.put("part-tokenChains-PrevState", partTokenChainsPrevState); tokenDetails.put("sender", senderDidIpfsHash); tokenDetails.put("proof", proofOfWork); + tokenDetails.put("distributedObject", Initiator.distributedObject); String doubleSpendString = tokenDetails.toString(); - TokenSenderLogger.debug("tokenDetails is " + tokenDetails.toString()); +// TokenSenderLogger.debug("tokenDetails is " + tokenDetails.toString()); String doubleSpend = calculateHash(doubleSpendString, "SHA3-256"); writeToFile(LOGGER_PATH + "doubleSpend", doubleSpend, false); @@ -942,14 +946,14 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) tokenObject.put("previousSender", tokenPreviousSender); 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"); - senderMutex = false; - return APIResponse; - } else { - TokenSenderLogger.debug("No Multiple Pins found, initating transcation"); - } +// +// if (Functions.multiplePinCheck(senderDidIpfsHash, tokenObject, ipfs) == 420) { +// APIResponse.put("message", "Multiple Owners Found. Kindly re-initiate transaction"); +// senderMutex = false; +// return APIResponse; +// } else { +// TokenSenderLogger.debug("No Multiple Pins found, initating transcation"); +// } /** * Sending Token Details to Receiver Receiver to authenticate Tokens (Double @@ -1112,8 +1116,7 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) TokenSenderLogger.debug("Consensus Reached"); senderDetails2Receiver.put("status", "Consensus Reached"); senderDetails2Receiver.put("quorumsign", InitiatorConsensus.quorumSignature.toString()); - senderDetails2Receiver.put("pledgeDetails", Initiator.pledgedTokensArray); - + senderDetails2Receiver.put("pledgeDetails", Initiator.pledgedTokensWithNodesArray); output.println(senderDetails2Receiver); TokenSenderLogger.debug("Quorum Signatures length " + InitiatorConsensus.quorumSignature.length()); @@ -1192,10 +1195,10 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) return APIResponse; } - TokenSenderLogger.debug("newBlocksForTokenChains is " + newBlocksForTokenChains); +// TokenSenderLogger.debug("newBlocksForTokenChains is " + newBlocksForTokenChains); TokenSenderLogger.debug(""); - TokenSenderLogger.debug("lastObJsonArray is " + lastObJsonArray.toString()); +// TokenSenderLogger.debug("lastObJsonArray is " + lastObJsonArray.toString()); JSONArray newTokenChainBlocks = new JSONArray(newBlocksForTokenChains); JSONArray hashAndSigns = new JSONArray(); @@ -1208,6 +1211,8 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) Map receiverChainMap = receiverLastObject.toMap(); senderChainMap.remove("pledgeToken"); receiverChainMap.remove("pledgeToken"); + senderChainMap.remove("distributedObject"); + receiverChainMap.remove("distributedObject"); TokenSenderLogger.debug("--------"); TokenSenderLogger.debug("senderChainMap " + senderChainMap.keySet().toString()); @@ -1221,7 +1226,7 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) TokenSenderLogger.debug(senderChainMap.equals(receiverChainMap) + " is the chainmap status"); - TokenSenderLogger.debug("signedChains is " + signedChains.toString()); +// TokenSenderLogger.debug("signedChains is " + signedChains.toString()); if (senderChainMap.equals(receiverChainMap)) { // String PvtKeySign = @@ -1484,7 +1489,7 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) output.println("New part token chain to be hashed"); output.println(chainArray.toString()); - TokenSenderLogger.debug("!@#$% 1: " + chainArray); +// TokenSenderLogger.debug("!@#$% 1: " + chainArray); String finalPartTokenChain_string; try { @@ -1586,7 +1591,7 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) } output.println("Old part token chains to be hashed"); output.println(partTokenChainsToBeSentForHashing.toString()); - TokenSenderLogger.debug("!@#$% 3: " + partTokenChainsToBeSentForHashing); +// TokenSenderLogger.debug("!@#$% 3: " + partTokenChainsToBeSentForHashing); String hashedPartTokenChains_string; try { @@ -1609,7 +1614,7 @@ public static JSONObject SendPartB(JSONObject signPayload, IPFS ipfs, int port) return APIResponse; } - TokenSenderLogger.debug("!@#$% 4: " + hashedPartTokenChains_string); +// TokenSenderLogger.debug("!@#$% 4: " + hashedPartTokenChains_string); JSONObject finalPartTokenChains = new JSONObject(hashedPartTokenChains_string); for (int i = 0; i < partTokens.length(); i++) { diff --git a/src/com/rubix/TokenTransfer/TransferPledge/Initiator.java b/src/com/rubix/TokenTransfer/TransferPledge/Initiator.java index 54b4617f..f98d66ee 100644 --- a/src/com/rubix/TokenTransfer/TransferPledge/Initiator.java +++ b/src/com/rubix/TokenTransfer/TransferPledge/Initiator.java @@ -1,5 +1,6 @@ package com.rubix.TokenTransfer.TransferPledge; +import com.jfoenix.controls.base.IFXLabelFloatControl; import com.rubix.Resources.IPFSNetwork; import io.ipfs.api.IPFS; import org.apache.log4j.Logger; @@ -11,6 +12,7 @@ import java.io.BufferedReader; import java.io.File; +import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; @@ -45,6 +47,10 @@ public class Initiator { public static String keyPass; public static JSONObject quorumHashObject = new JSONObject(); public static boolean pledged = false; + public static JSONObject distributedObject; + public static JSONArray alphaList = new JSONArray(); + public static JSONArray pledgedTokensWithNodesArray = new JSONArray(); + public static JSONArray pledgedTokensArray = new JSONArray(); @@ -52,7 +58,8 @@ public class Initiator { public static boolean abort = false; public static void resetVariables() { - + alphaList = new JSONArray(); + distributedObject = new JSONObject(); pledgedNodes = new JSONArray(); abortReason = new JSONObject(); tokenList = new JSONArray(); @@ -68,6 +75,7 @@ public static void resetVariables() { pledgedTokensArray = new JSONArray(); abort = false; pledged = false; + pledgedTokensWithNodesArray = new JSONArray(); } @@ -81,7 +89,7 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE // PledgeInitiatorLogger.debug("pledgeSetUp dataObject is // "+dataObject.toString()); - JSONArray alphaList = dataObject.getJSONArray("alphaList"); + alphaList = dataObject.getJSONArray("alphaList"); pvt = dataObject.getString("pvt"); tid = dataObject.getString("tid"); String keyPass = dataObject.getString("pvtKeyPass"); @@ -128,6 +136,7 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE if (qResponse != null) { JSONObject pledgeObject = new JSONObject(qResponse); + PledgeInitiatorLogger.debug("quorum response is "+pledgeObject.toString()+" from "+quorumID); if (pledgeObject.getString("pledge").equals("Tokens")) { PledgeInitiatorLogger.debug("Quorum " + quorumID + " is pledging Tokens"); JSONArray tokenDetails = pledgeObject.getJSONArray("tokenDetails"); @@ -152,11 +161,18 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE proofFile.mkdirs(); } writeToFile(proofFile.getAbsolutePath() + "/" + token + ".proof", proof, false); + proofFile = new File(TOKENCHAIN_PATH + "Proof/"+ token + ".proof", proof); + if(proofFile.exists()) { + PledgeInitiatorLogger.debug("Proof file added for" + token); + } String tokenName = lasObject.getString("pledgeToken"); String did = lasObject.getString("receiver"); - String tid = lasObject.getString("tid"); - pledged = Unpledge.verifyProof(tokenName, did, tid); + String txnID = lasObject.getString("tid"); + + + + pledged = Unpledge.verifyProof(tokenName, did, txnID); if (!pledged) { PledgeInitiatorLogger.debug("This token has already been pledged - Aborting"); @@ -165,9 +181,9 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE abortReason.put("Reason", "Token " + tokenObject.getString("tokenHash") + " has already been pledged"); - abort = true; +// abort = true; qSocket.close(); - return abort; +// return abort; } JSONObject pledgeNewObject = new JSONObject(); @@ -177,15 +193,20 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE pledgeNewObject.put("pledgeToken", tokenObject.getString("tokenHash")); pledgeNewObject.put("tokensPledgedFor", tokenList); pledgeNewObject.put("tokensPledgedWith", tokenObject.getString("tokenHash")); + pledgeNewObject.put("distributedObject", new JSONObject()); - // pledgedTokensArray.put(tokenObject.getString("tokenHash")); + pledgedTokensArray.put(tokenObject.getString("tokenHash")); tokenChain.put(pledgeNewObject); - PledgeInitiatorLogger.debug("@@@@@ Chain to hash: " + tokenChain); - - PledgeInitiatorLogger.debug("pledgeNewObject is " + pledgeNewObject); +// PledgeInitiatorLogger.debug("@@@@@ Chain to hash: " + tokenChain); +// +// PledgeInitiatorLogger.debug("pledgeNewObject is " + pledgeNewObject); String chainHashString = calculateHash(tokenChain.toString(), "SHA3-256"); hashesArray.put(chainHashString); + + if(proofFile.exists() && pledged) { + proofFile.delete(); + } } else { PledgeInitiatorLogger.debug("This token has already been pledged - Aborting"); @@ -193,9 +214,9 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE abortReason.put("Quorum", quorumID); abortReason.put("Reason", "Token " + tokenObject.getString("tokenHash") + " has already been pledged"); - abort = true; +// abort = true; qSocket.close(); - return abort; +// return abort; } } else { JSONObject pledgeNewObject = new JSONObject(); @@ -205,13 +226,14 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE pledgeNewObject.put("pledgeToken", tokenObject.getString("tokenHash")); pledgeNewObject.put("tokensPledgedFor", tokenList); pledgeNewObject.put("tokensPledgedWith", tokenObject.getString("tokenHash")); + pledgeNewObject.put("distributedObject", new JSONObject()); - // pledgedTokensArray.put(tokenObject.getString("tokenHash")); + pledgedTokensArray.put(tokenObject.getString("tokenHash")); tokenChain.put(pledgeNewObject); - PledgeInitiatorLogger.debug("@@@@@ Chain to hash: " + tokenChain); +// PledgeInitiatorLogger.debug("@@@@@ Chain to hash: " + tokenChain); - PledgeInitiatorLogger.debug("pledgeNewObject is " + pledgeNewObject); +// PledgeInitiatorLogger.debug("pledgeNewObject is " + pledgeNewObject); String chainHashString = calculateHash(tokenChain.toString(), "SHA3-256"); hashesArray.put(chainHashString); @@ -220,9 +242,9 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE quorumHashObject.put(quorumID, hashesArray); quorumWithHashesArray.put(quorumHashObject); quorumDetails.put("tokenDetails", tokenDetails); - - PledgeInitiatorLogger.debug("quorumHashObject: " + quorumHashObject.toString()); - PledgeInitiatorLogger.debug("quorumWithHashesArray is " + quorumWithHashesArray.toString()); +// +// PledgeInitiatorLogger.debug("quorumHashObject: " + quorumHashObject.toString()); +// PledgeInitiatorLogger.debug("quorumWithHashesArray is " + quorumWithHashesArray.toString()); PledgeInitiatorLogger.debug("tokensCount: " + tokensCount); quorumDetails.put("ID", quorumID); @@ -252,7 +274,9 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE qSocket.close(); return abort; } - return abort; + // return abort; + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + quorumID); + qSocket.close(); } PledgeInitiatorLogger.debug("Closing all connections..."); @@ -263,19 +287,33 @@ public static boolean pledgeSetUp(String data, IPFS ipfs, int PORT) throws JSONE } PledgeInitiatorLogger.debug("Token Count: " + tokensCount); +// if (tokensCount > 0) { +// PledgeInitiatorLogger.debug("Quorum Nodes cannot Pledge, Aborting..."); +// abortReason.put("Reason", "Quorum Nodes cannot Pledge, Aborting..."); +// abort = true; +// return true; +// } + + closeAllConnections(alphaList); if (tokensCount > 0) { - PledgeInitiatorLogger.debug("Quorum Nodes cannot Pledge, Aborting..."); - abortReason.put("Reason", "Quorum Nodes cannot Pledge, Aborting..."); - abort = true; - return true; - } - return abort; + PledgeInitiatorLogger.debug("Quorum nodes with lesser tokens to pledge, Exiting..."); + abortReason.put("Reason", "Quorum Nodes cannot Pledge, Aborting..."); + abort = true; + return abort; + }else { +// PledgeInitiatorLogger.debug("tokenList: " + tokenList + " pledgedTokensArray: " + pledgedTokensArray); + distributePledgeTokens(tokenList, pledgedTokensArray); +// PledgeInitiatorLogger.debug("Distributed Object after pledgeSetUp: " + distributedObject); + abort = false; + return abort; + } } public static boolean pledge(JSONArray pledgeDetails, double amount, int PORT) throws JSONException, UnknownHostException, IOException { Double tokensPledged = amount; + pledgedTokensArray = new JSONArray(); PledgeInitiatorLogger.debug("pledgeDetails in pledge is " + pledgeDetails.toString()); if (!abort) { @@ -343,6 +381,7 @@ public static boolean pledge(JSONArray pledgeDetails, double amount, int PORT) pledgeObject.put("pledgeToken", tokenHash); pledgeObject.put("tokensPledgedFor", tokenList); pledgeObject.put("tokensPledgedWith", tokenObject.getString("tokenHash")); + pledgeObject.put("distributedObject", new JSONObject()); tokenChain.put(pledgeObject); pledgedTokensArray.put(tokenObject.getString("tokenHash")); @@ -396,6 +435,10 @@ public static boolean pledge(JSONArray pledgeDetails, double amount, int PORT) PledgeInitiatorLogger.debug("newChains is " + newChains.toString()); } } + JSONObject nodesWithTokensObject = new JSONObject(); + nodesWithTokensObject.put("node", nodesToPledgeTokens.getJSONObject(j).getString("ID")); + nodesWithTokensObject.put("tokens", pledgedTokensArray); + pledgedTokensWithNodesArray.put(nodesWithTokensObject); /* * JSONObject jsonObject = pledgeDetails.getJSONObject(j); Iterator keys @@ -469,12 +512,56 @@ public static boolean pledge(JSONArray pledgeDetails, double amount, int PORT) } } + closeAllConnections(alphaList); + distributePledgeTokens(tokenList, pledgedTokensArray); if (tokensPledged > 0) abort = true; PledgeInitiatorLogger.debug("Quorum Verification with Tokens or Credits with Abort Status:" + Initiator.abort); return abort; } + + public static void closeAllConnections(JSONArray nodes) throws JSONException{ + for(int i = 0; i < nodes.length(); i++){ + IPFSNetwork.executeIPFSCommands("ipfs p2p close -t /p2p/" + nodes.getString(i)); + } + } + + public static boolean distributePledgeTokens(JSONArray transferTokens, JSONArray pledgedTokens) throws JSONException{ + distributedObject = new JSONObject(); + + PledgeInitiatorLogger.debug("<1> Transfer tokens: " + transferTokens); + PledgeInitiatorLogger.debug("<1> Pledge tokens: " + pledgedTokens); + + if(transferTokens.length() > pledgedTokens.length()) { + PledgeInitiatorLogger.debug("Only Whole Tokens"); + String partPledgedTokenString = pledgedTokens.getString(pledgedTokens.length()-1); + pledgedTokens.remove(pledgedTokens.length()-1); + + PledgeInitiatorLogger.debug("<2> Transfer tokens: " + transferTokens); + PledgeInitiatorLogger.debug("<2> Pledge tokens: " + pledgedTokens); + for(int i = 0; i < transferTokens.length(); i++) { + distributedObject.put(transferTokens.getString(i), pledgedTokens.getString(i)); + transferTokens.remove(i); + } + + PledgeInitiatorLogger.debug("<3> Transfer tokens: " + transferTokens); + PledgeInitiatorLogger.debug("<3> Pledge tokens: " + pledgedTokens); + + for (int i = 0; i < transferTokens.length(); i++) + distributedObject.put(transferTokens.getString(i), partPledgedTokenString); + + }else { + PledgeInitiatorLogger.debug("Parts Tokens Included"); + for(int i = 0; i < transferTokens.length(); i++) { + distributedObject.put(transferTokens.getString(i), pledgedTokens.getString(i)); + } + PledgeInitiatorLogger.debug("<4> Transfer tokens: " + transferTokens); + PledgeInitiatorLogger.debug("<4> Pledge tokens: " + pledgedTokens); + } + + return true; + } public static String fetchSign(JSONArray pledgeArray, String hash) throws JSONException { diff --git a/src/com/rubix/TokenTransfer/TransferPledge/Unpledge.java b/src/com/rubix/TokenTransfer/TransferPledge/Unpledge.java index b5b05fbb..bda06371 100644 --- a/src/com/rubix/TokenTransfer/TransferPledge/Unpledge.java +++ b/src/com/rubix/TokenTransfer/TransferPledge/Unpledge.java @@ -221,6 +221,7 @@ public static boolean hashMatch(List tokenProof, int[] index, String did } public static boolean verifyProof(String tokenName, String did, String trnxid) { + UnpledgeLogger.debug("Verifying proof for "+tokenName); List data = readData(Functions.TOKENCHAIN_PATH + "Proof/" + tokenName + ".proof"); boolean hashMatchStatus = hashMatch(data, pickIndexForValidation(data.size()), did, trnxid); UnpledgeLogger.debug("Hashmatch status is " + hashMatchStatus);