diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Communication/Receiver.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Communication/Receiver.java new file mode 100644 index 0000000000000000000000000000000000000000..bd57694bd0d9ac5d81c398377489823d3d64f156 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Communication/Receiver.java @@ -0,0 +1,107 @@ +package com.rubix.WAMPAC.Anomaly.Communication; + +import com.rubix.Resources.Functions; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; +import java.net.BindException; +import java.net.ServerSocket; +import java.net.Socket; + +import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.Functions.readFile; +import static com.rubix.WAMPAC.NMS.Constants.PathConstants.nmsFolder; + +public class Receiver implements Runnable { + static int PORT = 15060; + public static Logger Quorum = Logger.getLogger(Receiver.class); + + @Override + public void run() { + while (true){ + PropertyConfigurator.configure(Functions.LOGGER_PATH + "log4jWallet.properties"); + ServerSocket serverSocket = null; + Socket socket = null; + BufferedReader in = null; + PrintStream out= null; + JSONArray array = new JSONArray(); + + + try { + Quorum.debug("Quorum Listening on " + PORT); + serverSocket = new ServerSocket(PORT); + socket = serverSocket.accept(); + System.out.println("Accepted"); + in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + out = new PrintStream(socket.getOutputStream()); + String json = in.readLine(); + JSONObject temp = new JSONObject(json); + String did = temp.getString("did"); + temp.remove("did"); + File logFile = new File(nmsFolder+did); + if(!logFile.exists()){ + array = new JSONArray(); + logFile.mkdirs(); + }else { + File anomalyFile = new File(logFile + "\\anomaly.json"); + if(anomalyFile.exists()) { + array = new JSONArray(readFile(logFile + "\\anomaly.json")); + }else{ + anomalyFile.createNewFile(); + } + } + + array.put(temp); + + Functions.writeToFile(logFile+"\\anomaly.json",array.toString(),false); + + in.close(); + out.close(); + socket.close(); + serverSocket.close(); + + } + catch (BindException e) + { + try { + in.close(); + out.close(); + socket.close(); + serverSocket.close(); + e.printStackTrace(); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + } + catch (IOException e) { + try { + in.close(); + out.close(); + socket.close(); + serverSocket.close(); + e.printStackTrace(); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + + } catch (JSONException e) { + try { + in.close(); + out.close(); + socket.close(); + serverSocket.close(); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + e.printStackTrace(); + } + + } + } + + +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Communication/Sender.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Communication/Sender.java new file mode 100644 index 0000000000000000000000000000000000000000..9bab96e77774b197b2abcbc60f63707463f7fef0 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Communication/Sender.java @@ -0,0 +1,118 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package com.rubix.WAMPAC.Anomaly.Communication; + +import com.rubix.Resources.Functions; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; +import java.net.Socket; +import java.sql.Timestamp; +import java.time.Instant; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.WAMPAC.Anomaly.Resources.Functions.getVerifierIPList; +import static com.rubix.WAMPAC.NMS.Constants.PathConstants.nmsFolder; + +public class Sender { + public static Logger Sender = Logger.getLogger(Sender.class); + private static Socket[] qSocket; + private static PrintStream[] qOut; + private static BufferedReader[] qIn; + private static String[] quorumID; + + + public Sender() { + } + + public static void start(String data, int PORT) throws JSONException, IOException { + pathSet(); + PropertyConfigurator.configure(Functions.LOGGER_PATH + "log4jWallet.properties"); + + JSONArray quorumPeersObject = getVerifierIPList(); + + try { + + int i; + JSONObject dataObject = new JSONObject(); + Timestamp instant= Timestamp.from(Instant.now()); + String senderPeerID = getPeerID(DATA_PATH + "DID.json"); + String did = getValues(DATA_PATH + "DID.json", "didHash", "peerid", senderPeerID); + dataObject.put("anomaly",data); + dataObject.put("did",did); + dataObject.put("timestamp",instant); + Sender.debug("Sending trigger "+data); + + for (int j = 0; j < quorumPeersObject.length(); ++j) + quorumID[j] = quorumPeersObject.getString(j); + + + Thread[] quorumThreads = new Thread[quorumPeersObject.length()]; + + for (i = 0; i < quorumPeersObject.length(); ++i) { + int j = i; + quorumThreads[i] = new Thread(() -> { + try { + String var10001 = quorumID[j]; + Sender.debug("Connected to " + var10001); + qSocket[j] = new Socket(quorumID[j], PORT); + qIn[j] = new BufferedReader(new InputStreamReader(qSocket[j].getInputStream())); + qOut[j] = new PrintStream(qSocket[j].getOutputStream()); + qOut[j].println(dataObject); + + qOut[j].close(); + qIn[j].close(); + qSocket[j].close(); + } catch (IOException var13) { + + try { + qOut[j].close(); + qIn[j].close(); + } catch (IOException e) { + e.printStackTrace(); + } + Sender.error("IOException Occurred", var13); + var13.printStackTrace(); + } + + }); + quorumThreads[i].start(); + } + + + + File logFile = new File(nmsFolder + "anomaly.json"); + JSONArray array; + if (!logFile.exists()) { + array = new JSONArray(); + logFile.createNewFile(); + } + else + array = new JSONArray(readFile( nmsFolder+ "anomaly.json")); + + array.put(dataObject); + + + writeToFile(nmsFolder + "anomaly.json", array.toString(), false); + + } catch (JSONException var14) { + Sender.error("JSON Exception Occurred", var14); + var14.printStackTrace(); + } + + } + + static { + qSocket = new Socket[Functions.QUORUM_COUNT]; + qOut = new PrintStream[Functions.QUORUM_COUNT]; + qIn = new BufferedReader[Functions.QUORUM_COUNT]; + quorumID = new String[Functions.QUORUM_COUNT]; + } +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/NMS_main.java b/src/main/java/com/rubix/WAMPAC/Anomaly/NMS_main.java new file mode 100644 index 0000000000000000000000000000000000000000..ac7c902156157131e732e1ffbd8648ee704f6edd --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/NMS_main.java @@ -0,0 +1,70 @@ +package com.rubix.WAMPAC.Anomaly; + +import com.rubix.WAMPAC.Anomaly.Communication.Sender; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + + +import java.io.IOException; + +import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.WAMPAC.Anomaly.Resources.Functions.executeShell; + +public class NMS_main implements Runnable{ + @Override + public void run() { + try { + pathSet(); + executeShell("\n" + + "\n" + + "netsh advfirewall firewall add rule name=\"ICMP Allow incoming V4 echo request\" protocol=icmpv4:8,any dir=in action=allow"); + + while (true) { + Boolean response = (executeShell("Get-NetFirewallRule -DisplayName \"ICMP Allow incoming V4 echo request\" -erroraction 'silentlycontinue' | Select-Object Enabled").contains("True")) ? true : false; + if (!response) { + System.out.println("Triggered checkICMP"); + executeShell("Enable-NetFirewallRule -DisplayName \"ICMP Allow incoming V4 echo request\""); + + Sender.start("ICMP", 15060); + + } + response = (executeShell("Get-NetAdapter -Name \"Wi-Fi\" -erroraction 'silentlycontinue' | Select Status").contains("Up")) ? false : true; + if (!response) { + System.out.println("Triggered checkWIFI"); + executeShell("Disable-NetAdapter -Name \"Wi-Fi\" -Confirm:$false"); + Sender.start("WIFI", 15060); + } + response = (executeShell("Get-ItemProperty \"HKLM:\\SYSTEM\\CurrentControlSet\\services\\USBSTOR\" -name start -erroraction 'silentlycontinue' | Select-Object Start").contains("3")) ? false : true; + if (!response) { + System.out.println("Triggered checkUSB"); + executeShell("Set-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR\\\" -Name \"start\" -Value 4"); + Sender.start("USB", 15060); + } + response = (executeShell("Get-ChildItem -Path D:\\ -Filter \"*.exe\" ").isEmpty()) ? true : false; + if (!response) { + System.out.println("Triggered checkExeCert"); + JSONArray records = new JSONArray(executeShell("Get-ChildItem -Path D:\\ -Filter \"*.exe\" -Recurse | select Directory,Name | ConvertTo-Json")); + for (int i = 0; i < records.length(); i++) { + JSONObject record = records.getJSONObject(i); + JSONObject directory = record.getJSONObject("Directory"); + String dir = directory.getString("FullName"); + String filename = record.getString("Name"); + executeShell("Remove-Item \"" + dir + "\\" + filename + "\""); + } + + Sender.start("Uncertified EXE", 15060); + } + + + } +// ICMP icmp = new ICMP(); +// WIFI wifi = new WIFI(); +// USB usb = new USB(); +// PrivilageDrop privilageDrop = new PrivilageDrop(); +// NonCertExePurge nonCertExePurge = new NonCertExePurge(); + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Resources/Functions.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Resources/Functions.java new file mode 100644 index 0000000000000000000000000000000000000000..fce1364d64018836392e597a87fa6188af167c40 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Resources/Functions.java @@ -0,0 +1,35 @@ +package com.rubix.WAMPAC.Anomaly.Resources; + +import com.profesorfalken.jpowershell.PowerShell; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; + +import static com.rubix.Resources.Functions.DATA_PATH; +import static com.rubix.Resources.Functions.readFile; + +public class Functions { + public static JSONArray getVerifierIPList() throws JSONException { + JSONObject temp; + JSONArray ip = new JSONArray(); + File file = new File(DATA_PATH+"vip.json"); + if(file.exists()) { + JSONArray verifiers = new JSONArray(readFile(DATA_PATH + "vip.json")); + for (int i = 0; i < verifiers.length(); i++) { + temp = verifiers.getJSONObject(i); + if (temp.getString("role").equals("Verifier")) { + ip.put(temp.getString("ip")); + } + } + return ip; + } + else return new JSONArray(); + } + + public static String executeShell(String command) { + String response = PowerShell.executeSingleCommand(command).getCommandOutput(); + return response; + } +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/ICMP.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/ICMP.java new file mode 100644 index 0000000000000000000000000000000000000000..2d1706af895d0982bc7a7a88a294536d75f7c681 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/ICMP.java @@ -0,0 +1,29 @@ +package com.rubix.WAMPAC.Anomaly.Trackers; + + +import com.rubix.WAMPAC.Anomaly.Communication.Sender; +import org.json.JSONException; + +import java.io.IOException; + +import static com.rubix.WAMPAC.Anomaly.Resources.Functions.executeShell; +import static com.rubix.WAMPAC.Anomaly.Trackers.Monitor.checkICMP; + +public class ICMP implements Runnable { + + @Override + public void run() { + try { + executeShell("\n" + + "\n" + + "netsh advfirewall firewall add rule name=\"ICMP Allow incoming V4 echo request\" protocol=icmpv4:8,any dir=in action=allow"); + while (true) { + checkICMP(); + executeShell("Enable-NetFirewallRule -DisplayName \"ICMP Allow incoming V4 echo request\""); + Sender.start("ICMP", 15060); + } + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/Monitor.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/Monitor.java new file mode 100644 index 0000000000000000000000000000000000000000..700681f52f89a58ed7e6d2bee820509f0a724ea5 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/Monitor.java @@ -0,0 +1,47 @@ +package com.rubix.WAMPAC.Anomaly.Trackers; + + +import static com.rubix.WAMPAC.Anomaly.Resources.Functions.executeShell; + +public class Monitor { + public static void checkICMP(){ + System.out.println("Monitoring checkICMP"); + Boolean response = true; + while(response) + response = (executeShell("Get-NetFirewallRule -DisplayName \"ICMP Allow incoming V4 echo request\" -erroraction 'silentlycontinue' | Select-Object Enabled").contains("True"))?true:false; + System.out.println("Triggered checkICMP"); + } + + public static void checkWIFI(){ + System.out.println("Monitoring checkWIFI"); + Boolean response = true; + while(response) + response = (executeShell("Get-NetAdapter -Name \"Wi-Fi\" -erroraction 'silentlycontinue' | Select Status").contains("Up"))?false:true; + System.out.println("Triggered checkWIFI"); + } + + public static void checkUSB(){ + System.out.println("Monitoring checkUSB"); + Boolean response = true; + while(response) + response = (executeShell("Get-ItemProperty \"HKLM:\\SYSTEM\\CurrentControlSet\\services\\USBSTOR\" -name start -erroraction 'silentlycontinue' | Select-Object Start").contains("3"))?false:true; + System.out.println("Triggered checkUSB"); + } + + public static void checkLocalAccount(){ + System.out.println("Monitoring checkLocalAccount"); + Boolean response = true; + while(response) + response = (executeShell("net localgroup administrators | select -skip 6 -erroraction 'silentlycontinue' | ? {$_ -and $_ -notmatch 'successfully|^administrator|^msp.localadmin|^xyz.devadmin$'} ").isEmpty())?true:false; + System.out.println("Triggered checkLocalAccount"); + } + + public static void checkExeCert(){ + System.out.println("Monitoring checkExeCert"); + Boolean response = true; + while(response) + response = (executeShell("Get-ChildItem -Path D:\\ -Filter \"*.exe\" ").isEmpty())?true:false; + System.out.println("Triggered checkExeCert"); + } + +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/NonCertExePurge.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/NonCertExePurge.java new file mode 100644 index 0000000000000000000000000000000000000000..24de4951b8b0bae9aa2c945fa391b814960afff0 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/NonCertExePurge.java @@ -0,0 +1,37 @@ +package com.rubix.WAMPAC.Anomaly.Trackers; + + +import com.rubix.WAMPAC.Anomaly.Communication.Sender; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; + +import static com.rubix.WAMPAC.Anomaly.Resources.Functions.executeShell; +import static com.rubix.WAMPAC.Anomaly.Trackers.Monitor.checkExeCert; + + +public class NonCertExePurge implements Runnable { + + @Override + public void run() { + try { + while (true) { + checkExeCert(); + JSONArray records = new JSONArray(executeShell("Get-ChildItem -Path D:\\ -Filter \"*.exe\" -Recurse | select Directory,Name | ConvertTo-Json")); + for (int i = 0; i < records.length(); i++){ + JSONObject record = records.getJSONObject(i); + JSONObject directory = record.getJSONObject("Directory"); + String dir = directory.getString("FullName"); + String filename = record.getString("Name"); + executeShell("Remove-Item \""+dir+"\\"+filename+"\""); + } + + Sender.start("Uncertified EXE", 15060); + } + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/PrivilageDrop.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/PrivilageDrop.java new file mode 100644 index 0000000000000000000000000000000000000000..0f82e920f62cc226e9cf0d11c7f0a7c0eae81da4 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/PrivilageDrop.java @@ -0,0 +1,30 @@ +package com.rubix.WAMPAC.Anomaly.Trackers; + + +import com.rubix.WAMPAC.Anomaly.Communication.Sender; +import org.json.JSONArray; +import org.json.JSONException; + +import java.io.IOException; + +import static com.rubix.WAMPAC.Anomaly.Resources.Functions.executeShell; +import static com.rubix.WAMPAC.Anomaly.Trackers.Monitor.checkLocalAccount; + +public class PrivilageDrop implements Runnable { + + @Override + public void run() { + try { + while (true) { + checkLocalAccount(); + JSONArray users = new JSONArray(executeShell("net localgroup administrators | select -skip 6 | ? {$_ -and $_ -notmatch 'successfully|^administrator|^msp.localadmin|^xyz.devadmin$'} | ConvertTo-Json")); + for (int i = 0; i < users.length(); i++) + executeShell("net localgroup administrators'"+users.getString(i)+"'/delete"); + + Sender.start("PrivilageDrop", 15060); + } + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/USB.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/USB.java new file mode 100644 index 0000000000000000000000000000000000000000..09a68a76bbcf446d7600ccf13b6094266c666f8f --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/USB.java @@ -0,0 +1,27 @@ +package com.rubix.WAMPAC.Anomaly.Trackers; + + +import com.rubix.WAMPAC.Anomaly.Communication.Sender; +import org.json.JSONException; + +import java.io.IOException; + +import static com.rubix.WAMPAC.Anomaly.Resources.Functions.executeShell; +import static com.rubix.WAMPAC.Anomaly.Trackers.Monitor.checkUSB; + + +public class USB implements Runnable { + + @Override + public void run() { + try { + while (true) { + checkUSB(); + executeShell("Set-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR\\\" -Name \"start\" -Value 4"); + Sender.start("USB", 15060); + } + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/WIFI.java b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/WIFI.java new file mode 100644 index 0000000000000000000000000000000000000000..31085c36801bde722adfee1556d3c06f309b6a15 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Anomaly/Trackers/WIFI.java @@ -0,0 +1,27 @@ +package com.rubix.WAMPAC.Anomaly.Trackers; + + +import com.rubix.WAMPAC.Anomaly.Communication.Sender; +import org.json.JSONException; + +import java.io.IOException; + +import static com.rubix.WAMPAC.Anomaly.Resources.Functions.executeShell; +import static com.rubix.WAMPAC.Anomaly.Trackers.Monitor.checkWIFI; + + +public class WIFI implements Runnable { + + @Override + public void run() { + try { + while (true) { + checkWIFI(); + executeShell("Disable-NetAdapter -Name \"Wi-Fi\" -Confirm:$false"); + Sender.start("WIFI", 15060); + } + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/Controller/DID.java b/src/main/java/com/rubix/WAMPAC/Controller/DID.java new file mode 100644 index 0000000000000000000000000000000000000000..06fdae82587d82138162b4bd5a9f2dd263356451 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Controller/DID.java @@ -0,0 +1,606 @@ +package com.rubix.WAMPAC.Controller; + +import com.rubix.Resources.Functions; +import com.rubix.Resources.IPFSNetwork; +import com.rubix.WAMPAC.Anomaly.Communication.Receiver; +import com.rubix.WAMPAC.Anomaly.NMS_main; +import com.rubix.WAMPAC.DID.RequestTokens; +import com.rubix.WAMPAC.DID.VerifierListen; +import com.rubix.WAMPAC.DID.VerifierUserListen; +import com.rubix.WAMPAC.DID.ipClass; +import com.rubix.WAMPAC.NMS.ExecuteTask; +import com.rubix.WAMPAC.NMS.LogsConsensus.LogQuorumConsensus; +import com.rubix.WAMPAC.NMS.Recovery.RecoveryAssistQuorum; +import com.rubix.WAMPAC.DID.User.*; +import com.rubix.WAMPAC.DID.Verifier.*; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static RubixDID.DIDCreation.DIDimage.createDID; +import static com.rubix.Resources.APIHandler.*; +import static com.rubix.Resources.APIHandler.onlinePeersCount; +import static com.rubix.Resources.Functions.*; +import static com.rubix.WAMPAC.DID.DIDFunctions.*; +import static com.rubix.WAMPAC.FileAccess.FileAccessFunctions.createRbxDrive; +import static com.rubix.WAMPAC.NMS.Constants.PathConstants.*; +import static com.rubix.WAMPAC.Controller.NMSCollection.nmsStart; +import static com.rubix.WAMPAC.NMSCollection.Paths.createCollectionFolder; + +@CrossOrigin(origins = "http://localhost:1898") +@RestController +public class DID { + private static final String USER_AGENT = "Mozilla/5.0"; + private static String role = ""; + public static boolean listenThreads = false; + public static boolean userNMSinit = false; + public static boolean verifierNmsListen = false; + + @RequestMapping(value = "/checkDidExists", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String checkDidExists() throws JSONException { + System.out.println("Called /checkDidStatus"); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + setDir(); + Path path = Paths.get(dirPath); + boolean isDir = Files.isDirectory(path); + if (isDir) { + setConfig(); + File config = new File(configPath); + if (config.exists()) { + pathSet(); + File didFile = new File(DATA_PATH + "DID.json"); + if (didFile.exists()) { + System.out.println("DID exists"); + contentObject.put("payload", "Success"); + } + else { + System.out.println("DID.json doesn't exists"); + contentObject.put("payload", "Failure"); + } + + } else { + System.out.println("config.json doesn't exists"); + contentObject.put("payload", "Failure"); + } + } else { + System.out.println("RUBIX folder doesn't exists"); + contentObject.put("payload", "Failure"); + } + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/checkDidVerified", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String checkDidVerified() throws JSONException { + System.out.println("Called /checkDidVerified"); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + boolean verifiedStatus = false; + + pathSet(); + File vipFile = new File(DATA_PATH + "vip.json"); + if (!vipFile.exists()) + contentObject.put("payload", "Failure"); + + else { + String vipContent = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipContent); + + String myIp = ipClass.getIP(); + System.out.println("/checkDidVerified IP Address: " + myIp); + + System.out.println(myIp); + for (int i = 0; i < vipArray.length(); i++) { + if (vipArray.getJSONObject(i).getString("ip").equals(myIp)) + if (vipArray.getJSONObject(i).getString("status").equals("true")) + verifiedStatus = true; + } + if (verifiedStatus) + contentObject.put("payload", "Success"); + + else + contentObject.put("payload", "Failure"); + + } + + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/checkRole", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String checkRole() throws JSONException { + System.out.println("Called /checkRole"); + Functions.pathSet(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + File file = new File(DATA_PATH + "vip.json"); + if(file.exists()) { + System.out.println("Inside"); + String vipContent = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipContent); + String myIp = ipClass.getIP(); + System.out.println("/checkRole IP Address: " + myIp); + for (int i = 0; i < vipArray.length(); i++) { + if (vipArray.getJSONObject(i).getString("ip").equals(myIp)) + role = vipArray.getJSONObject(i).getString("role"); + } + contentObject.put("payload", role); + }else + System.out.println("Outside"); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/getIp", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String getIp() throws JSONException{ + System.out.println("Called /getIp"); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + String myIp = ipClass.getIP(); + System.out.println("/getIp IP Address: " + myIp); + contentObject.put("payload", myIp); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/getMac", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String getMac() throws JSONException { + System.out.println("Called /getMac"); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + contentObject.put("payload", macAddress()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/create", method = RequestMethod.POST, + produces = {"application/json", "application/xml"}) + public String Create(@RequestParam("image") MultipartFile imageFile, @RequestParam("data") String value) throws Exception { + System.out.println("Called /create"); + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + JSONObject didResult = createDID(value, imageFile.getInputStream()); + contentObject.put("payload", didResult); + + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/getInfo", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String getInfo() throws JSONException { + System.out.println("Called /getInfo"); + pathSet(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + File file = new File(DATA_PATH + "DID.json"); + if(file.exists()) { + String didFile = readFile(DATA_PATH + "DID.json"); + JSONArray didArray = new JSONArray(didFile); + JSONObject didObject = didArray.getJSONObject(0); + + String myIp = ipClass.getIP(); + System.out.println("/getInfo IP Address: " + myIp); + didObject.put("ip", myIp); + + contentObject.put("payload", didObject); + } + else + contentObject.put("payload", new JSONObject()); + + + + + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/getNetworkInfo", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String getNetworkInfo() throws JSONException { + System.out.println("Called /getNetworkInfo"); + pathSet(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + File file = new File(DATA_PATH + "DID.json"); + if(file.exists()) { + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + JSONArray verifiersArray = new JSONArray(); + for (int i = 0; i < vipArray.length(); i++) { + if (vipArray.getJSONObject(i).getString("role").equals("Verifier")) { + JSONObject verifierObject = vipArray.getJSONObject(i); + verifierObject.remove("role"); + verifierObject.remove("status"); + verifiersArray.put(verifierObject); + } + } + + contentObject.put("payload", verifiersArray); + } + else + contentObject.put("payload", new JSONArray()); + + + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + + @RequestMapping(value = "/sync", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String sync() throws Exception { + System.out.println("Called /sync"); + Functions.pathSet(); + IPFSNetwork.executeIPFSCommands("ipfs daemon"); + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + String url = "http://172.17.128.102:9090/getrole?ip="; + + String myip = ipClass.getIP(); + System.out.println("/sync IP Address: " + myip); + url = url + myip; + URL obj = new URL(url); + System.out.println(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // Setting basic get request + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", USER_AGENT); + 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"); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String response; + StringBuffer stringBuffer = new StringBuffer(); + + while ((response = in.readLine()) != null) { + stringBuffer.append(response); + } + in.close(); + role = stringBuffer.toString(); + + if (role.equals("Verifier")) { + //Listen on all threads + if(!listenThreads) { + verifierVerifyListen(); + verifierUserListen(); + verifierSendData(); + listenThreads = true; + } + + Functions.launch(); + if (vipSync()) { + if(rulesSync()){ + System.out.println("Successful - check Sync Status in the log"); + contentObject.put("payload", "Success"); + }else{ + System.out.println("Launch Failed Rules"); + contentObject.put("payload", "Failed to sync. Try again."); + } + + } else { + System.out.println("Launch Failed VIP"); + contentObject.put("payload", "Failed to sync. Try again."); + } + } else if (role.equals("User")) { + contentObject.put("payload", getDataFromVerifier.getData()); + } + + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/enroll", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String enroll() throws Exception { + System.out.println("Called /enroll"); + Functions.pathSet(); + IPFSNetwork.executeIPFSCommands("ipfs daemon"); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + String myip = ipClass.getIP(); + System.out.println("/enroll IP Address: " + myip); + + if (role.equals("Verifier")) { + //verifierInitiate + contentObject.put("payload", verifierDID(myip)); + } else if (role.equals("User")) { + //userInitiate + contentObject.put("payload", userDID(myip)); + + } + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + public static void verifierVerifyListen() { + VerifierListen verifierListen = new VerifierListen(); + Thread verThread = new Thread(verifierListen); + verThread.start(); + + } + + public static void verifierUserListen() { + VerifierUserListen verifierUserListen = new VerifierUserListen(); + Thread verifierUserThread = new Thread(verifierUserListen); + verifierUserThread.start(); + } + + public static void verifierSendData() { + sendToUser sendToUser = new sendToUser(); + Thread send = new Thread(sendToUser); + send.start(); + } + + public static void LogQuorumConsensusListen() { + pathSet(); + LogQuorumConsensus q1 = new LogQuorumConsensus(); + Thread logQuorumConsensus = new Thread(q1); + logQuorumConsensus.start(); + } + + public static void RecoveryAssistQuorumListen() { + pathSet(); + RecoveryAssistQuorum q1 = new RecoveryAssistQuorum(); + Thread recoveryThread = new Thread(q1); + recoveryThread.start(); + } + + public static void NMSLoggerInit() { + pathSet(); + ExecuteTask q1 = new ExecuteTask(); + Thread executeThread = new Thread(q1); + executeThread.start(); + } + + public static void AnomalyReceiver(){ + Receiver q1 = new Receiver(); + Thread executeThread = new Thread(q1); + executeThread.start(); + } + + public static void NMSClient(){ + NMS_main q1 = new NMS_main(); + Thread executeThread = new Thread(q1); + executeThread.start(); + } + + + @RequestMapping(value = "/verifierGetUserVip", method = RequestMethod.POST, + produces = {"application/json", "application/xml"}) + public String verifierGetUserVip(@RequestBody Details details) throws Exception { + + JSONObject vipDetails = new JSONObject(); + vipDetails.put("peerid", details.getPeerid()); + vipDetails.put("ip", details.getIp()); + vipDetails.put("role", details.getRole()); + vipDetails.put("status", details.getStatus()); + + JSONObject result = new JSONObject(); + result.put("data", addUserVipListen.listen(vipDetails)); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/verifierGetUserData", method = RequestMethod.POST, + produces = {"application/json", "application/xml"}) + public String verifierGetUserData(@RequestBody Details details) throws Exception { + JSONObject dataDetails = new JSONObject(); + dataDetails.put("peerid", details.getPeerid()); + dataDetails.put("didHash", details.getDidHash()); + dataDetails.put("walletHash", details.getWalletHash()); + System.out.println(dataDetails); + + JSONObject result = new JSONObject(); + result.put("data", addUserDataTableListen.listen(dataDetails)); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/modifyIP", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String modifyIP() throws JSONException, IOException { + Functions.pathSet(); + IPFSNetwork.executeIPFSCommands("ipfs daemon"); + + JSONObject result = new JSONObject(); + + String ip = ipClass.getIP(); + System.out.println("/modifyIp IP Address: " + ip); + if (getRole(ip).equals("Verifier")) { + //Call Contract - File Access + JSONObject contentObject = new JSONObject(); + result.put("data", contentObject); + } else { + result.put("data", "Access Denied"); + } + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/p2pclose", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String p2pclose() throws JSONException { + IPFSNetwork.executeIPFSCommands("ipfs p2p close --all"); + System.out.println("P2P close Successful - check p2p ls for streams"); + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/getOnlinePeers", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String getOnlinePeers() throws IOException, JSONException, InterruptedException { + Functions.pathSet(); + IPFSNetwork.executeIPFSCommands("ipfs daemon"); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", peersOnlineStatus()); + contentObject.put("count", peersOnlineStatus().length()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/getContactsList", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String getContactsList() throws JSONException{ + Functions.pathSet(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", contacts()); + contentObject.put("count", contacts().length()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/requestTokens", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String requestTokens() throws JSONException{ + Functions.pathSet(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + File tokenListFile = new File(WALLET_DATA_PATH + "tokenList.json"); + if(!tokenListFile.exists()) + contentObject.put("payload", RequestTokens.getTokens()); + else + contentObject.put("payload", "Success"); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/getDashboard", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public String getDashboard() throws JSONException, IOException, InterruptedException { + pathSet(); + createCollectionFolder(); + createRbxDrive(); + + IPFSNetwork.executeIPFSCommands("ipfs daemon"); + File nms = new File(nmsFolder); + if (!nms.exists()) + nms.mkdirs(); + + FileAccess.listen(); + + String roleString = checkRole(); + JSONObject roleObject = new JSONObject(roleString); + System.out.println("Role Object: " + roleString); + String role = roleObject.getJSONObject("data").getString("payload"); + if (role.contains("Verifier")) { + if (!listenThreads) { + verifierVerifyListen(); + verifierUserListen(); + verifierSendData(); + listenThreads = true; + } + if(!verifierNmsListen){ + LogQuorumConsensusListen(); + RecoveryAssistQuorumListen(); + AnomalyReceiver(); + verifierNmsListen = true; + } + } + else if(role.contains("User")){ + File recovered = new File(RecoveryFolder); + if (!recovered.exists()) + recovered.mkdirs(); + File logs = new File(logsFolder); + if (!logs.exists()) + logs.mkdirs(); + File backup = new File(backupFolder); + if (!backup.exists()) + backup.mkdirs(); + if(!userNMSinit) { + userNMSinit = true; + NMSLoggerInit(); + NMSClient(); + } + } + + if(!nmsStart) + NMSCollection.start(); + + JSONArray contactsObject = contacts(); + int contactsCount = contactsObject.length(); + + JSONArray accountInfo = accountInformation(); + JSONObject accountObject = accountInfo.getJSONObject(0); + + JSONArray dateTxn = txnPerDay(); + JSONObject dateTxnObject = dateTxn.getJSONObject(0); + + accountObject.put("onlinePeers", onlinePeersCount()); + accountObject.put("contactsCount", contactsCount); + accountObject.put("transactionsPerDay", dateTxnObject); + + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", accountObject); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + +} diff --git a/src/main/java/com/rubix/WAMPAC/Controller/FileAccess.java b/src/main/java/com/rubix/WAMPAC/Controller/FileAccess.java new file mode 100644 index 0000000000000000000000000000000000000000..95933dac8a930fe0f105c6b1cd46cf35aa22b81e --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Controller/FileAccess.java @@ -0,0 +1,419 @@ +package com.rubix.WAMPAC.Controller; + + +import com.rubix.Resources.Functions; +import com.rubix.Resources.IPFSNetwork; +import com.rubix.WAMPAC.DID.ipClass; +import com.rubix.WAMPAC.FileAccess.Listen; +import io.ipfs.api.IPFS; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.simple.parser.ParseException; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.WAMPAC.FileAccess.FileAccessFunctions.*; +import static com.rubix.WAMPAC.FileAccess.UIFunctions.*; + +@CrossOrigin(origins = "http://localhost:1898") +@RestController +public class FileAccess { + public static boolean fileListen = false; + + @PostMapping(value = "/createContract", produces = {"application/json", "application/xml"}) + public static String createContract(@RequestParam("num") int num, @RequestParam("did") String did, @RequestParam("ip") String ip, @RequestParam("writeCount") int writeCount) throws JSONException, IOException, InterruptedException { + System.out.println("Called /createContract"); + pathSet(); + createRbxDrive(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + JSONArray jsonArray = new JSONArray(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("did", did); + jsonObject.put("ip", ip); + jsonObject.put("writeCount", writeCount); + jsonArray.put(jsonObject); + File file = new File(DRIVE_PATH + "contractData"+num+".json"); + if(!file.exists()) { + file.createNewFile(); + writeToFile(file.toString(), jsonArray.toString(), false); + } else { + String fileData = readFile(file.toString()); + JSONArray jsonArray1 = new JSONArray(fileData); + jsonArray1.put(jsonObject); + writeToFile(file.toString(), jsonArray1.toString(), false); + } + contentObject.put("response", "Contract Data Updated"); + + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/launch", produces = {"application/json", "application/xml"}) + public static String getLaunch(@RequestParam("file") MultipartFile file, @RequestParam("contractData") JSONArray contractData) throws JSONException, IOException, NoSuchAlgorithmException, ParseException, InterruptedException { + System.out.println("Called /launch"); + System.out.println("Data contract data: " + contractData); + Functions.pathSet(); + createRbxDrive(); + IPFSNetwork.executeIPFSCommands("ipfs daemon"); + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + String didFile = readFile(DATA_PATH + "DID.json"); + JSONArray didArray = new JSONArray(didFile); + JSONObject didObject = didArray.getJSONObject(0); + String myDID = didObject.getString("didHash"); + System.out.println("DID: " + myDID); + + boolean didInList = false; + for(int i = 0; i < contractData.length(); i++){ + if(contractData.getJSONObject(i).getString("did").equals(myDID)) + didInList = true; + } + + if(didInList) { + System.out.println("push file into IPFS – fileHash"); + IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + byte[] bytes = file.getBytes(); + Path path = Paths.get(DRIVE_PATH + file.getOriginalFilename()); + Files.write(path, bytes); + String fileHash = IPFSNetwork.add(path.toString(), ipfs); + System.out.println("IPFS FileHash : " + fileHash); +// +// byte[] contractBytes = contractDataFile.getBytes(); +// Path contractPath = Paths.get(DRIVE_PATH + contractDataFile.getOriginalFilename()); +// Files.write(contractPath, contractBytes); +// +// String contractDataString = readFile(DRIVE_PATH + contractDataFile.getOriginalFilename()); + //JSONArray contractData = new JSONArray(contractDataString); + JSONObject hashObject = new JSONObject(); + String token = ""; + + //JSONObject - fileHash, bytecodehash, contractdata, mydid + hashObject.put("did", myDID); + hashObject.put("fileHash", fileHash); + hashObject.put("contractData", contractData); + + //Assign a token + System.out.println("Assigning New Token to the file"); + File tokenFile = new File(WALLET_DATA_PATH + "tokenList.json"); + if(tokenFile.exists()) { + + String tokenList = readFile(WALLET_DATA_PATH + "tokenList.json"); + + JSONArray tokensArray = new JSONArray(tokenList); + if (!(tokensArray.length() == 0)) + token = tokensArray.getJSONObject(0).getString("tokenHash"); + System.out.println("Assigned Token: " + token); + + System.out.println("adding token & tokenchain into IPFS"); + + File tokenSingleFile = new File(TOKENS_PATH + token); + if(tokenSingleFile.exists()) { + IPFSNetwork.add(TOKENS_PATH + token, ipfs); + IPFSNetwork.add(TOKENCHAIN_PATH + token + ".json", ipfs); + + System.out.println("Calling Sign Init function for Signatures"); + System.out.println("Data Passed as arguments: token:" + token + " " + "hashObject: " + hashObject); + if (signInitiator(token, hashObject, "launch", file.getOriginalFilename())) { + System.out.println("Signatures Received and Token Assigned"); + + //remove token from tokenList + tokensArray.remove(0); + System.out.println("Token Removed from tokenList.json" + token); + writeToFile(WALLET_DATA_PATH + "tokenList.json", tokensArray.toString(), false); + + //write into fileTokenList + File tokenfile = new File(DRIVE_PATH + "fileTokenList.json"); + if (!tokenfile.exists()) { + tokenfile.createNewFile(); + writeToFile(tokenfile.getPath(), new JSONArray().toString(), false); + } + + String newTokenData = readFile(tokenfile.getPath()); + JSONArray newTokenArray = new JSONArray(newTokenData); + JSONObject newTokenObject = new JSONObject(); + newTokenObject.put("tokenHash", token); + newTokenArray.put(newTokenObject); + writeToFile(tokenfile.getPath(), newTokenArray.toString(), false); + + System.out.println("Token Added to fileTokenList.json"); + contentObject.put("response", "Launch successful, token : " + token); + System.out.println("Launch successful"); + } else { + contentObject.put("response", "Launch Failed"); + System.out.println("Launch Failed"); + } + }else{ + contentObject.put("response", "No tokens available"); + } + }else{ + contentObject.put("response", "No tokens available"); + } + }else{ + contentObject.put("response", "Select your DID for the contract"); + } + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/listen", produces = {"application/json", "application/xml"}) + public static String listen() throws JSONException, IOException { + + Functions.pathSet(); + createRbxDrive(); + if(!fileListen){ + Listen listen = new Listen(); + Thread thread = new Thread(listen); + thread.start(); + fileListen = true; + } + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("response", "Listening for Launch / update"); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/update", produces = {"application/json", "application/xml"}) + public static String getUpdate(@RequestParam("newfile") MultipartFile newFile, @RequestParam("token") String token) throws JSONException, IOException, InterruptedException { + System.out.println("Called /update"); + System.out.println("Data token: " + token); + + Functions.pathSet(); + createRbxDrive(); + IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + System.out.println("Adding new file into IPFS"); + //Push newFile + byte[] newbytes = newFile.getBytes(); + Path newpath = Paths.get(DRIVE_PATH + newFile.getOriginalFilename()); + Files.write(newpath, newbytes); + String newfileHash = IPFSNetwork.add(newpath.toString(), ipfs); + + System.out.println("Checking token validity and launch status"); + if (tokenCheck(token)) { + System.out.println("Fetching the contract details, prev version of the file using token"); + //fetch oldfile, tokenChain, contractData corresponding to token from contracts.json + String contractFile = readFile(DRIVE_PATH + "Contracts.json"); + JSONArray contractDataFile = new JSONArray(contractFile); + String oldfileHash = ""; + JSONArray contractData = new JSONArray(); + for (int i = 0; i < contractDataFile.length(); i++) { + JSONObject innerObject = contractDataFile.getJSONObject(i); + if ((innerObject.getString("token")).equals(token)) { + oldfileHash = innerObject.getString("fileHash"); + contractData = innerObject.getJSONArray("contractData"); + } + } + System.out.println("prev file hash : " + oldfileHash + " " + "contractdata: " + contractData); + //JSONObject - InitDID, newfileipfshash, prevFilehash + String didFile = readFile(DATA_PATH + "DID.json"); + JSONArray didArray = new JSONArray(didFile); + JSONObject didObject = didArray.getJSONObject(0); + String myDID = didObject.getString("didHash"); + + JSONObject details = new JSONObject(); + details.put("did", myDID); + details.put("oldHash", oldfileHash); + details.put("fileHash", newfileHash); + details.put("contractData", contractData); +// InetAddress myIP = InetAddress.getLocalHost(); +// String ip = myIP.getHostAddress(); +// System.out.println("IP Check" + ip); + + String myIp = ipClass.getIP(); + System.out.println("/update IP Address: " + myIp); + details.put("ip",myIp); + + //Check verifyWriteCount(InitDID) from contractdata + System.out.println("Verifying write count"); + if (verifyWriteCount(myDID, contractData, myIp)) { + System.out.println("Access Permissions granted"); + System.out.println("calling sign init for signature creation"); + System.out.println("Arguments passed: " + "token: " + token + " " + "details for sign: " + details); + //SignInitiator(Token, JSONObject, TC) + if (signInitiator(token, details, "update", "")) { + System.out.println("Signatures obtained"); + + //adding new file to datapath + File oldfile = new File(DRIVE_PATH + oldfileHash); + if (oldfile.exists()) + oldfile.delete(); + + System.out.println("Adding file shared to data path"); + String newData = IPFSNetwork.get(newfileHash, ipfs); + writeToFile(DRIVE_PATH + newfileHash, newData, false); + + System.out.println("Updating contract with new data"); + updateContract(myDID, newfileHash, token); + System.out.println("Update Done"); + contentObject.put("response", "update successful"); + } else { + System.out.println("Invalid Signatures"); + contentObject.put("response", "Invalid Signatures"); + } + } else { + System.out.println("No permission to update"); + contentObject.put("response", "No permission to update"); + } + } else { + System.out.println("Invalid token / file not launched"); + contentObject.put("response", "Invalid token / file not launched"); + } + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + //======================================================================================================// + @GetMapping(value = "/getSharedFilesCount", produces = {"application/json", "application/xml"}) + public static String getSharedFilesCount() throws JSONException { + System.out.println("Called /getSharedFilesCount"); + Functions.pathSet(); + createRbxDrive(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + int fileCount = sharedFilesCount(); + if(fileCount > 0) + contentObject.put("response", fileCount); + else + contentObject.put("response", 0); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getSharedFiles", produces = {"application/json", "application/xml"}) + public static String getSharedFiles() throws JSONException, IOException { + System.out.println("Called /getSharedFiles"); + Functions.pathSet(); + createRbxDrive(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + ArrayList<String> filesList = sharedFilesList(); + contentObject.put("response", filesList); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/getSharedFileDetails", produces = {"application/json", "application/xml"}) + public static String getSharedFileDetails(@RequestParam("fileName") String fileName) throws JSONException { + System.out.println("Called /getSharedFileDetails"); + Functions.pathSet(); + createRbxDrive(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + JSONObject data = sharedFileDetails(fileName); + contentObject.put("response", data); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/getSharedFileMetaData", produces = {"application/json", "application/xml"}) + public static String getSharedFileMetaData(@RequestParam("fileName") String fileName) throws JSONException { + System.out.println("Called /getSharedFileMetaData"); + Functions.pathSet(); + createRbxDrive(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + JSONObject metaData = sharedFileMetaData(fileName); + contentObject.put("response", metaData); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getDidList", produces = {"application/json", "application/xml"}) + public static String getDidList() throws JSONException { + System.out.println("Called /getDidList"); + Functions.pathSet(); + createRbxDrive(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + String didFile = readFile(DATA_PATH + "DID.json"); + JSONArray myDidArray = new JSONArray(didFile); + String myDid = myDidArray.getJSONObject(0).getString("didHash"); + + String dataTableFile = readFile(DATA_PATH + "Datatable.json"); + JSONArray didArray = new JSONArray(dataTableFile); + JSONArray didResultArray = new JSONArray(); + didResultArray.put(myDid); + for(int i = 0; i < didArray.length(); i++){ + if(!didArray.getJSONObject(i).getString("didHash").equals(myDid)) + didResultArray.put(didArray.getJSONObject(i).getString("didHash")); + } + contentObject.put("response", didResultArray); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/getIpFromDid", produces = {"application/json", "application/xml"}) + public static String getIpFromDid(@RequestParam("did") String did) throws JSONException { + System.out.println("Called /getIpFromDid"); + Functions.pathSet(); + createRbxDrive(); + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + + String ip = "", peerid = ""; + + String dataTableFile = readFile(DATA_PATH + "Datatable.json"); + JSONArray didArray = new JSONArray(dataTableFile); + for(int i = 0; i < didArray.length(); i++){ + JSONObject vipObject = didArray.getJSONObject(i); + if(vipObject.getString("didHash").equals(did)) + peerid = vipObject.getString("peerid"); + } + + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + for(int i = 0; i < vipArray.length(); i++){ + JSONObject vipObject = vipArray.getJSONObject(i); + if(vipObject.getString("peerid").equals(peerid)) + ip = vipObject.getString("ip"); + } + + if(ip.equals("")) + contentObject.put("response", "Not a valid member"); + else + contentObject.put("response", ip); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + +} + + diff --git a/src/main/java/com/rubix/WAMPAC/Controller/NMS.java b/src/main/java/com/rubix/WAMPAC/Controller/NMS.java new file mode 100644 index 0000000000000000000000000000000000000000..7eff9c67dd8e629c83349b6d51b13279555d27ec --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Controller/NMS.java @@ -0,0 +1,590 @@ +package com.rubix.WAMPAC.Controller; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import java.util.*; + + +import static com.rubix.Resources.Functions.*; +import static com.rubix.WAMPAC.NMS.Constants.PathConstants.backupFolder; +import static com.rubix.WAMPAC.NMS.Constants.PathConstants.nmsFolder; +import static com.rubix.WAMPAC.NMSCollection.Paths.MemoryFile; +import static com.rubix.WAMPAC.NMSCollection.Paths.MemoryFolder; + +@RestController +public class NMS { + + @PostMapping(value = "/addBackup", produces = {"application/json", "application/xml"}) + public static String addBackup(@RequestParam("file") MultipartFile file) throws JSONException, IOException { + System.out.println("Called /addBackup"); + pathSet(); + JSONObject result = new JSONObject(); + + double fileSize = file.getSize() * 0.00000095367432; + if (fileSize < 1) { + byte[] bytes = file.getBytes(); + Path path = Paths.get(backupFolder + file.getOriginalFilename()); + Files.write(path, bytes); + + File filePath = new File(path.toString()); + if (filePath.exists()) + result.put("data", "Success"); + else + result.put("data", "Failed to backup file. Try again later."); + + } else + result.put("data", "Upload smaller file (2MB). Try again later."); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/getNmsUser", produces = {"application/json", "application/xml"}) + public static String getNmsUser(@RequestParam("index") int index) throws JSONException { + System.out.println("Called /getNmsUser"); + pathSet(); + JSONObject finalObject = new JSONObject(); + File logsFile = new File(nmsFolder + "log.json"); + if (logsFile.exists()) { + String logFileContent = readFile(nmsFolder + "log.json"); + System.out.println(nmsFolder + "log.json"); + JSONArray logsArray = new JSONArray(logFileContent); + JSONArray results = new JSONArray(); + HashMap<String, String> map = new HashMap<>(); + + for (int i = logsArray.length() - 1 - (index * 50); map.size() < 10 && i >= 0; i--) + map.put(logsArray.getJSONObject(i).getString("tid"), logsArray.getJSONObject(i).getString("status")); + + for (Map.Entry<String, String> entry : map.entrySet()) { + JSONObject object = new JSONObject(); + object.put("tid", entry.getKey()); + object.put("status", entry.getValue()); + results.put(object); + } + System.out.println(results.length()); + finalObject.put("count", results.length()); + finalObject.put("payload", results); + } else { + finalObject.put("count", 0); + finalObject.put("payload", new JSONArray()); + } + JSONObject result = new JSONObject(); + result.put("data", finalObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/getTxnDetails", produces = {"application/json", "application/xml"}) + public static String getTxnDetails(@RequestParam("tid") String tid) throws JSONException { + System.out.println("Called /getTxnDetails"); + pathSet(); + JSONObject result = new JSONObject(); + File file = new File(nmsFolder + "log.json"); + if (file.exists()) { + String logFileContent = readFile(nmsFolder + "log.json"); + JSONArray logsArray = new JSONArray(logFileContent); + JSONArray signArray = new JSONArray(); + JSONObject resultObject = new JSONObject(); + for (int i = 0; i < logsArray.length(); i++) { + if (logsArray.getJSONObject(i).getString("tid").equals(tid)) { + signArray.put(logsArray.getJSONObject(i).getString("sign")); + resultObject = logsArray.getJSONObject(i); + } + } + + resultObject.put("sign", signArray); + result.put("data", resultObject); + } else + result.put("data", new JSONObject()); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getBackupFiles", produces = {"application/json", "application/xml"}) + public static String getBackupFiles() throws JSONException { + System.out.println("Called /getBackupFiles"); + pathSet(); + JSONObject result = new JSONObject(); + JSONArray backupList = new JSONArray(); + + File folder = new File(backupFolder); + File[] listOfFiles = folder.listFiles(); + + for (int i = 0; i < listOfFiles.length; i++) { + backupList.put(listOfFiles[i].getName()); + } + result.put("data", backupList); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getStatusList", produces = {"application/json", "application/xml"}) + public static String getStatusList() throws JSONException { + System.out.println("Called /getStatusList"); + pathSet(); + JSONObject result = new JSONObject(); + JSONArray resultArray = new JSONArray(); + JSONArray usersArrays = new JSONArray(); + File folder = new File(nmsFolder); + File[] listOfFiles = folder.listFiles(); + boolean invalid = false; + for (int i = 0; i < listOfFiles.length; i++) { + if (listOfFiles[i].isDirectory()) { + if (!listOfFiles[i].getName().startsWith("Qm")) + invalid = true; + usersArrays.put(listOfFiles[i].getName()); + } + } + System.out.println(invalid); + if (!invalid) { + for (int i = 0; i < usersArrays.length(); i++) { + File file = new File(nmsFolder + usersArrays.getString(i) + "/log.json"); + if (file.exists()) { + String userDetails = readFile(nmsFolder + usersArrays.getString(i) + "/log.json"); + JSONArray jsonArray = new JSONArray(userDetails); + JSONObject object = new JSONObject(); + object.put("did", usersArrays.getString(i)); + object.put("status", jsonArray.getJSONObject(jsonArray.length() - 1).getString("status")); + + resultArray.put(object); + } + } + result.put("data", resultArray); + } else + result.put("data", "Operation not allowed"); + + + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getPieData", produces = {"application/json", "application/xml"}) + public static String getPieData() throws JSONException { + System.out.println("Called /getPieData"); + pathSet(); + JSONObject result = new JSONObject(); + JSONArray countObject = new JSONArray(); + JSONArray usersArrays = new JSONArray(); + File folder = new File(nmsFolder); + File[] listOfFiles = folder.listFiles(); + boolean invalid = false; + for (int i = 0; i < listOfFiles.length; i++) { + if (listOfFiles[i].isDirectory()) { + if (!listOfFiles[i].getName().startsWith("Qm")) + invalid = true; + usersArrays.put(listOfFiles[i].getName()); + } + } + int unsafeCount = 0; + int safeCount = 0; + if (!invalid) { + + for (int i = 0; i < usersArrays.length(); i++) { + File file = new File(nmsFolder + usersArrays.getString(i) + "/log.json"); + if (file.exists()) { + String userDetails = readFile(nmsFolder + usersArrays.getString(i) + "/log.json"); + System.out.println(userDetails); + JSONArray jsonArray = new JSONArray(userDetails); + if (jsonArray.getJSONObject(jsonArray.length() - 1).getString("status").contains("restore")) + unsafeCount++; + else + safeCount++; + } + + } + countObject.put(unsafeCount); + countObject.put(safeCount); + } else + result.put("data", "Operation not allowed"); + + result.put("data", countObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/getDidTransactions", produces = {"application/json", "application/xml"}) + public static String getDidTransactions(@RequestParam("did") String did) throws JSONException { + System.out.println("Called /getDidTransactions"); + pathSet(); + JSONObject result = new JSONObject(); + File logFileData = new File(nmsFolder + did + "/log.json"); + if (logFileData.exists()) { + String logFile = readFile(nmsFolder + did + "/log.json"); + JSONArray userLogArray = new JSONArray(logFile); + + JSONArray usersArrays = new JSONArray(); + for (int i = 0; i < userLogArray.length(); i++) { + JSONObject object = new JSONObject(); + object.put("tid", userLogArray.getJSONObject(i).getString("tid")); + object.put("status", userLogArray.getJSONObject(i).getString("status")); + + usersArrays.put(object); + } + result.put("data", usersArrays); + } else { + result.put("data", new JSONArray()); + } + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @PostMapping(value = "/getDidTxnDetails", produces = {"application/json", "application/xml"}) + public static String getDidTxnDetails(@RequestParam("did") String did, @RequestParam("tid") String tid) throws JSONException { + System.out.println("Called /getDidTxnDetails"); + pathSet(); + JSONObject result = new JSONObject(); + File logFileData = new File(nmsFolder + did + "/log.json"); + if (logFileData.exists()) { + String logFile = readFile(nmsFolder + did + "/log.json"); + JSONArray userLogArray = new JSONArray(logFile); + + JSONArray usersArrays = new JSONArray(); + for (int i = 0; i < userLogArray.length(); i++) { + if (userLogArray.getJSONObject(i).getString("tid").equals(tid)) { + JSONObject object = new JSONObject(); + object.put("did", did); + object.put("tid", tid); + object.put("logHash", userLogArray.getJSONObject(i).getString("loghash")); + object.put("sign", userLogArray.getJSONObject(i).getString("sign")); + object.put("share", userLogArray.getJSONObject(i).getString("share")); + + usersArrays.put(object); + } + } + result.put("data", usersArrays); + } else { + result.put("data", new JSONArray()); + } + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/unsafeCount", produces = {"application/json", "application/xml"}) + public static String unsafeCount() throws JSONException, IOException { + System.out.println("Called /unsafeCount"); + pathSet(); + JSONObject result = new JSONObject(); + int unsafeCount = 0; + File unsafeFile = new File(nmsFolder + "unsafe.json"); + if (unsafeFile.exists()) { + String userRecordsFile = readFile(nmsFolder + "unsafe.json"); + JSONArray recordArray = new JSONArray(userRecordsFile); + + for (int i = 0; i < recordArray.length(); i++) { + Iterator<String> keys = recordArray.getJSONObject(i).keys(); + String did = keys.next(); + unsafeCount = unsafeCount + recordArray.getJSONObject(i).getInt(did); + } + } + result.put("data", unsafeCount); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/mostUnsafe", produces = {"application/json", "application/xml"}) + public static String mostUnsafe() throws JSONException, IOException { + System.out.println("Called /mostUnsafe"); + pathSet(); + JSONObject result = new JSONObject(); + + File unsafeFile = new File(nmsFolder + "unsafe.json"); + if (unsafeFile.exists()) { + String userRecordsFile = readFile(nmsFolder + "unsafe.json"); + JSONArray recordArray = new JSONArray(userRecordsFile); + + JSONArray resultArray = new JSONArray(); + + int index; + while (recordArray.length() > 0) { + int mostUnsafe = 0; + index = 0; + for (int i = 0; i < recordArray.length(); i++) { + JSONObject temp = recordArray.getJSONObject(i); + Iterator<String> keys = temp.keys(); + String did = keys.next(); + if (recordArray.getJSONObject(i).getInt(did) > mostUnsafe) { + mostUnsafe = recordArray.getJSONObject(i).getInt(did); + index = i; + } + } + + resultArray.put(recordArray.getJSONObject(index)); + recordArray.remove(index); + } + result.put("data", resultArray); + } else + result.put("data", new JSONArray()); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/networkUsersCount", produces = {"application/json", "application/xml"}) + public static String networkUsersCount() throws JSONException { + System.out.println("Called /networkUsersCount"); + pathSet(); + JSONObject result = new JSONObject(); + JSONArray usersArrays = new JSONArray(); + File folder = new File(nmsFolder); + File[] listOfFiles = folder.listFiles(); + boolean invalid = false; + for (int i = 0; i < listOfFiles.length; i++) { + if (listOfFiles[i].isDirectory()) { + if (!listOfFiles[i].getName().startsWith("Qm")) + invalid = true; + usersArrays.put(listOfFiles[i].getName()); + } + } + if (!invalid) { + result.put("data", usersArrays.length()); + } else + result.put("data", "Operation not allowed"); + + + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getAnomalyListUser", produces = {"application/json", "application/xml"}) + public static String getAnomalyListUser() throws JSONException { + System.out.println("Called /getAnomalyListUser"); + pathSet(); + JSONObject result = new JSONObject(); + File anomalyFile = new File(nmsFolder + "anomaly.json"); + JSONArray anomalyArray; + if (!anomalyFile.exists()) { + anomalyArray = new JSONArray(); + } else { + String anomalyData = readFile(nmsFolder + "anomaly.json"); + anomalyArray = new JSONArray(anomalyData); + } + + result.put("data", anomalyArray); + + + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getAnomalyListVerifier", produces = {"application/json", "application/xml"}) + public static String getAnomalyListVerifier() throws JSONException { + System.out.println("Called /getAnomalyListVerifier"); + pathSet(); + JSONObject result = new JSONObject(); + JSONArray usersArrays = new JSONArray(); + File folder = new File(nmsFolder); + File[] listOfFiles = folder.listFiles(); + boolean invalid = false; + for (int i = 0; i < listOfFiles.length; i++) { + if (listOfFiles[i].isDirectory()) { + if (!listOfFiles[i].getName().startsWith("Qm")) + invalid = true; + usersArrays.put(listOfFiles[i].getName()); + } + } + JSONArray anomalyArray = new JSONArray(); + if (!invalid) { + for (int i = 0; i < usersArrays.length(); i++) { + File userAnomalyFile = new File(nmsFolder + usersArrays.getString(i) + "/anomaly.json"); + if (userAnomalyFile.exists()) { + String anomalyData = readFile(nmsFolder + usersArrays.getString(i) + "/anomaly.json"); + JSONArray userAnomalyArray = new JSONArray(anomalyData); + for (int j = 0; j < userAnomalyArray.length(); j++) { + JSONObject dataObject = userAnomalyArray.getJSONObject(j); + dataObject.put("did", usersArrays.getString(i)); + anomalyArray.put(dataObject); + } + } + + } + result.put("data", anomalyArray); + } else + result.put("data", "Operation not allowed"); + + + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + + @GetMapping(value = "/getLogsCount", produces = {"application/json", "application/xml"}) + public static String getLogsCount() throws JSONException { + System.out.println("Called /getLogsCount"); + pathSet(); + JSONArray logsArray = new JSONArray(); + File logsFile = new File(nmsFolder + "log.json"); + if (logsFile.exists()) { + String logFileContent = readFile(nmsFolder + "log.json"); + System.out.println(nmsFolder + "log.json"); + logsArray = new JSONArray(logFileContent); + } + JSONObject result = new JSONObject(); + result.put("data", logsArray.length()/5); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/latestSystemStatus", produces = {"application/json", "application/xml"}) + public static String latestSystemStatus() throws JSONException { + System.out.println("Called /latestSystemStatus"); + pathSet(); + String status = ""; + File logsFile = new File(nmsFolder + "log.json"); + if (logsFile.exists()) { + String logFileContent = readFile(nmsFolder + "log.json"); + System.out.println(nmsFolder + "log.json"); + JSONArray logsArray = new JSONArray(logFileContent); + status = logsArray.getJSONObject(logsArray.length() - 1).getString("status"); + } + JSONObject result = new JSONObject(); + result.put("data", status); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getLatestAnomalies", produces = {"application/json", "application/xml"}) + public static String getLatestAnomalies() throws JSONException { + System.out.println("Called /getLatestAnomalies"); + pathSet(); + JSONObject result = new JSONObject(); + JSONArray finalArray = new JSONArray(); + File anomalyFile = new File(nmsFolder + "anomaly.json"); + JSONArray anomalyArray; + if (anomalyFile.exists()) { + String anomalyData = readFile(nmsFolder + "anomaly.json"); + anomalyArray = new JSONArray(anomalyData); + if (anomalyArray.length() <= 3) + finalArray = anomalyArray; + else { + int i = anomalyArray.length() - 1, j = 0; + while (j < 3) { + finalArray.put(anomalyArray.getJSONObject(i)); + i--; + j++; + } + } + } + + result.put("data", finalArray); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/anomalyBarChart", produces = {"application/json", "application/xml"}) + public static String anomalyBarChart() throws JSONException { + System.out.println("Called /anomalyBarChart"); + pathSet(); + JSONObject contentObject = new JSONObject(); + + JSONArray timeArray = new JSONArray(); + File file = new File(nmsFolder + "anomaly.json"); + if (file.exists()) { + String anomalyFile = readFile(nmsFolder + "anomaly.json"); + JSONArray anomalyArray = new JSONArray(anomalyFile); + int len = anomalyArray.length() - 1; + int j = 0; + while (j < anomalyArray.length()) { + JSONObject object = anomalyArray.getJSONObject(len); + timeArray.put(object.getString("timestamp")); + j++; + len--; + } + + HashSet<String> hashSet = new HashSet(); + for (int i = 0; i < timeArray.length(); i++) { + String output = timeArray.getString(i).substring(0, 10); + hashSet.add(output); + } + + JSONArray timeCountArray = new JSONArray(); + for (String language : hashSet) { + timeCountArray.put(new JSONObject().put("time", language)); + } + for(int i = 0; i < timeCountArray.length(); i++){ + int count = 0; + for(int k =0; k < timeArray.length(); k++){ + String time = anomalyArray.getJSONObject(k).getString("timestamp").substring(0, 10); + if(time.equals(timeCountArray.getJSONObject(i).getString("time"))) + count++; + } + timeCountArray.getJSONObject(i).put("count", count); + } + + contentObject.put("payload", timeCountArray); + }else + contentObject.put("payload", new JSONArray()); + + JSONObject result = new JSONObject(); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getLastLogTime", produces = {"application/json", "application/xml"}) + public static String getLastLogTime() throws JSONException{ + System.out.println("Called /getLastLogTime"); + + System.out.println(MemoryFolder + MemoryFile); + JSONObject result = new JSONObject(); + File logFile = new File(MemoryFolder + MemoryFile); + if (logFile.exists()) { + String logsContent = readFile(MemoryFolder + MemoryFile); + JSONArray logsArray = new JSONArray(logsContent); + System.out.println(logsArray); + System.out.println(logsArray.getJSONObject(logsArray.length()-1)); + System.out.println(logsArray.getJSONObject(logsArray.length()-1).getString("time")); + result.put("data", logsArray.getJSONObject(logsArray.length()-1).getString("time")); + } + else + result.put("data", ""); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @GetMapping(value = "/getTokenCount", produces = {"application/json", "application/xml"}) + public static String getTokenCount() throws JSONException{ + System.out.println("Called /getTokenCount"); + pathSet(); + JSONObject result = new JSONObject(); + File tokenFile = new File(WALLET_DATA_PATH + "tokenList.json"); + if (tokenFile.exists()) { + String tokenContent = readFile(WALLET_DATA_PATH + "tokenList.json"); + JSONArray tokenArray = new JSONArray(tokenContent); + result.put("data", tokenArray.length()); + } + else + result.put("data", 0); + + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + +} diff --git a/src/main/java/com/rubix/WAMPAC/Controller/NMSCollection.java b/src/main/java/com/rubix/WAMPAC/Controller/NMSCollection.java new file mode 100644 index 0000000000000000000000000000000000000000..4f6aba7ac25192f149abcbf2da35708c3233a20e --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/Controller/NMSCollection.java @@ -0,0 +1,369 @@ +package com.rubix.WAMPAC.Controller; + + +import com.rubix.WAMPAC.NMSCollection.DescriptorThread; +import com.rubix.WAMPAC.NMSCollection.DiskThread; +import com.rubix.WAMPAC.NMSCollection.FileSystemThread; +import com.rubix.WAMPAC.NMSCollection.MemoryThread; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.io.File; +import java.io.IOException; +import java.net.SocketException; +import java.net.UnknownHostException; + +import static com.rubix.Resources.Functions.pathSet; +import static com.rubix.Resources.Functions.readFile; +import static com.rubix.WAMPAC.NMSCollection.DetectUSB.usbDetectMain; +import static com.rubix.WAMPAC.NMSCollection.NetworkInfo.networkInfo; +import static com.rubix.WAMPAC.NMSCollection.Paths.*; +import static com.rubix.WAMPAC.NMSCollection.PowerInfo.powerInfo; +import static com.rubix.WAMPAC.NMSCollection.ProcessInfo.processInfo; +import static com.rubix.WAMPAC.NMSCollection.Sessions.sessionInfo; +import static com.rubix.WAMPAC.NMSCollection.TCPandUDPStats.tcpudpStats; +import static com.rubix.WAMPAC.NMSCollection.Functions.*; + + +@CrossOrigin(origins = "http://localhost:1898") +@RestController +public class NMSCollection { + public static boolean nmsStart = false; + @RequestMapping(value = "/start", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String start() throws JSONException { + + nmsStart = true; + pathSet(); + DiskThread diskThread = new DiskThread(); + Thread disk = new Thread(diskThread); + disk.start(); + + MemoryThread memoryThread = new MemoryThread(); + Thread memory = new Thread(memoryThread); + memory.start(); + + DescriptorThread descriptorThread = new DescriptorThread(); + Thread descriptor = new Thread(descriptorThread); + descriptor.start(); + + FileSystemThread fileSystemThread = new FileSystemThread(); + Thread fileSystem = new Thread(fileSystemThread); + fileSystem.start(); + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("message", "Setup Complete"); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + + } + + @RequestMapping(value = "/USBLogging", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String USBLogging() throws Throwable { + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", usbDetectMain()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + + @RequestMapping(value = "/Memory", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String Memory() throws JSONException { + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + File file = new File(MemoryFolder + MemoryFile); + if(file.exists()) { + String memoryFile = readFile(MemoryFolder + MemoryFile); + JSONArray diskArray = new JSONArray(memoryFile); + + JSONObject resultObject = new JSONObject(); + JSONArray availableMemoryArray = new JSONArray(); + JSONArray timeArray = new JSONArray(); + JSONArray usedVirtualMemoryArray = new JSONArray(); + int len = diskArray.length() - 1; + System.out.println(len); + if (len < 30) { + int j = 0; + while (j < len) { + JSONObject object = diskArray.getJSONObject(len - j); + availableMemoryArray.put(object.getLong("availableMem")); + timeArray.put(object.getString("time")); + usedVirtualMemoryArray.put(object.getLong("usedVirtualMem")); + j++; + } + } else { + int i = 0; + while (i < 30) { + JSONObject object = diskArray.getJSONObject(len - i); + availableMemoryArray.put(object.getLong("availableMem")); + timeArray.put(object.getString("time")); + usedVirtualMemoryArray.put(object.getLong("usedVirtualMem")); + i++; + } + } + resultObject.put("totalMemory", diskArray.getJSONObject(len).getLong("totalMemory")); + resultObject.put("totalVirtualMemory", diskArray.getJSONObject(len).getLong("totalVirtualMemory")); + resultObject.put("availableMem", availableMemoryArray); + resultObject.put("time", timeArray); + resultObject.put("usedVirtualMem", usedVirtualMemoryArray); + + contentObject.put("payload", resultObject); + } + + else contentObject.put("payload", new JSONObject()); + + + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + + + } + + @RequestMapping(value = "/PowerInfo", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String PowerInfo() throws JSONException { + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", powerInfo()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/SessionsInfo", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String SessionsInfo() throws JSONException { + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", sessionInfo()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/FileDescriptor", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String FileDescriptor() throws JSONException, IOException, InterruptedException { + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + File file = new File(DescriptorFolder + DescriptorFile); + if(file.exists()) { + String descriptorFile = readFile(DescriptorFolder + DescriptorFile); + JSONArray diskArray = new JSONArray(descriptorFile); + + JSONObject resultObject = new JSONObject(); + JSONArray openDescriptorsArray = new JSONArray(); + JSONArray timeArray = new JSONArray(); + JSONArray MaxDescriptorsArray = new JSONArray(); + int len = diskArray.length() - 1; + System.out.println(len); + if (len < 30) { + int j = 0; + while (j < len) { + JSONObject object = diskArray.getJSONObject(len - j); + openDescriptorsArray.put(object.getLong("openDescriptors")); + timeArray.put(object.getString("time")); + MaxDescriptorsArray.put(object.getLong("MaxDescriptors")); + j++; + } + } else { + int i = 0; + while (i < 30) { + JSONObject object = diskArray.getJSONObject(len - i); + openDescriptorsArray.put(object.getLong("openDescriptors")); + timeArray.put(object.getString("time")); + MaxDescriptorsArray.put(object.getLong("MaxDescriptors")); + i++; + } + } + resultObject.put("openDescriptors", openDescriptorsArray); + resultObject.put("time", timeArray); + resultObject.put("MaxDescriptors", MaxDescriptorsArray); + + contentObject.put("payload", resultObject); + }else + contentObject.put("payload", new JSONObject()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + + } + + @RequestMapping(value = "/FileSystem", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String FileSystem() throws JSONException, IOException, InterruptedException { + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + File file = new File(FileSystemFolder + FileSystemFile); + if(file.exists()) { + String fileSystemFile = readFile(FileSystemFolder + FileSystemFile); + JSONArray diskArray = new JSONArray(fileSystemFile); + + JSONObject resultObject = new JSONObject(); + JSONArray freeSpaceArray = new JSONArray(); + JSONArray usableSpaceArray = new JSONArray(); + JSONArray totalSpaceArray = new JSONArray(); + int len = diskArray.length() - 1; + if (len < 30) { + int j = 0; + while (j < len) { + JSONObject object = diskArray.getJSONObject(len - j); + freeSpaceArray.put(object.getLong("freeSpace")); + usableSpaceArray.put(object.getLong("usableSpace")); + totalSpaceArray.put(object.getLong("totalSpace")); + j++; + } + } else { + int i = 0; + while (i < 30) { + JSONObject object = diskArray.getJSONObject(len - i); + freeSpaceArray.put(object.getLong("freeSpace")); + usableSpaceArray.put(object.getLong("usableSpace")); + totalSpaceArray.put(object.getLong("totalSpace")); + i++; + } + } + resultObject.put("fileStoreName", diskArray.getJSONObject(len).getString("fileStoreName")); + resultObject.put("freeSpace", freeSpaceArray); + resultObject.put("usableSpace", usableSpaceArray); + resultObject.put("totalSpace", totalSpaceArray); + + + contentObject.put("payload", resultObject); + }else + contentObject.put("payload", new JSONObject()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/DiskStorage", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String DiskStorage() throws JSONException, IOException, InterruptedException { + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + File file = new File(DiskFolder + DiskFile); + if(file.exists()) { + String diskFile = readFile(DiskFolder + DiskFile); + JSONArray diskArray = new JSONArray(diskFile); + + JSONObject resultObject = new JSONObject(); + JSONArray writeBytesArray = new JSONArray(); + JSONArray readBytesArray = new JSONArray(); + JSONArray timeArray = new JSONArray(); + int len = diskArray.length() - 1; + if (len < 30) { + int j = 0; + while (j < len) { + JSONObject object = diskArray.getJSONObject(len - j); + writeBytesArray.put(object.getLong("writeBytes")); + readBytesArray.put(object.getLong("readBytes")); + timeArray.put(object.getString("time")); + j++; + } + } else { + int i = 0; + while (i < 30) { + JSONObject object = diskArray.getJSONObject(len - i); + writeBytesArray.put(object.getLong("writeBytes")); + readBytesArray.put(object.getLong("readBytes")); + timeArray.put(object.getString("time")); + i++; + } + } + resultObject.put("diskName", diskArray.getJSONObject(len).getString("diskName")); + resultObject.put("size", diskArray.getJSONObject(len).getLong("size")); + resultObject.put("writeBytes", writeBytesArray); + resultObject.put("readBytes", readBytesArray); + resultObject.put("time", timeArray); + + contentObject.put("payload", resultObject); + } + else + contentObject.put("payload", new JSONObject()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + + } + + @RequestMapping(value = "/TCPUDPStats", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String TCPUDPStats() throws JSONException { + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", tcpudpStats()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/NetworkInfo", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String NetworkInfo() throws SocketException, UnknownHostException, JSONException { + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", networkInfo()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/ProcessInfo", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String ProcessInfo() throws JSONException { + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", processInfo()); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + @RequestMapping(value = "/InstalledApps", method = RequestMethod.GET, + produces = {"application/json", "application/xml"}) + public static String InstalledApps() throws JSONException, IOException { + + File file = new File(CollectionFolder + "InstalledSoft.csv"); + if(!file.exists()) + Runtime.getRuntime().exec( "cmd /c start cmd.exe /c \"wmic product get name,vendor /format:csv >"+CollectionFolder+"InstalledSoft.csv\" " ); + + JSONObject result = new JSONObject(); + JSONObject contentObject = new JSONObject(); + contentObject.put("payload", readDataFromCSV(CollectionFolder + "InstalledSoft.csv")); + result.put("data", contentObject); + result.put("message", ""); + result.put("status", "true"); + return result.toString(); + } + + +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/ContactNodes.java b/src/main/java/com/rubix/WAMPAC/DID/ContactNodes.java new file mode 100644 index 0000000000000000000000000000000000000000..90ccff9c6645add237e0b1f311573ec465b526f8 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/ContactNodes.java @@ -0,0 +1,268 @@ +package com.rubix.WAMPAC.DID; + +import com.rubix.AuthenticateNode.Interact; +import com.rubix.Resources.IPFSNetwork; +import io.ipfs.api.IPFS; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; +import java.net.Socket; +import java.util.ArrayList; + +import static com.rubix.AuthenticateNode.Authenticate.verifySignature; +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.Functions.calculateHash; +import static com.rubix.Resources.IPFSNetwork.add; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; + +public class ContactNodes { + public static volatile JSONArray signatureDetails = new JSONArray(); + public static volatile JSONArray rawDetails = new JSONArray(); + public static volatile int rawCount, loopCount =0; + public static String fileHash; + public static Logger ContactNodesLogger = Logger.getLogger(ContactNodes.class); + public static volatile int verifiedcount; + public static volatile int nonverifiedcount; + private static final Object countLock = new Object(); + private static final Object signLock = new Object(); + + public static synchronized void rawDataSync(JSONObject data){ + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + synchronized (countLock) { + rawDetails.put(data); + ContactNodesLogger.debug("added to raw details in sync block: \n" + rawDetails.toString()); + } + } + + public static synchronized void signatureSync(JSONObject data, String initiatordid, JSONArray contractMembers) throws JSONException, IOException { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + synchronized (signLock) { + signatureDetails.put(data); + + if(signatureDetails.length() == contractMembers.length()){ + JSONObject signObject = new JSONObject(); + signObject.put("did", initiatordid); + signObject.put("data", rawDetails); + String mySign = sign(signObject.toString()); + + JSONObject responseObject = new JSONObject(); + responseObject.put("did", initiatordid); + responseObject.put("signature", mySign); + responseObject.put("status", "Verifiers Matched"); + signatureDetails.put(responseObject); + } + + ContactNodesLogger.debug("added to signature details in sync block: \n" + signatureDetails.toString()); + } + } + + + public static boolean contact(JSONArray contractMembers, JSONObject datatosign, String initiatordid) throws JSONException, IOException { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + int sizeofverifierpeers = contractMembers.length(); + PrintStream[] cout = new PrintStream[sizeofverifierpeers]; + BufferedReader[] cin = new BufferedReader[sizeofverifierpeers]; + Socket[] senderSocket = new Socket[sizeofverifierpeers]; + IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + ArrayList<String> DID = new ArrayList<>(); + ArrayList<String> PeerID = new ArrayList<>(); + ArrayList<String> appName = new ArrayList<>(); + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + Thread[] verifierThreads = new Thread[contractMembers.length()]; + verifiedcount=0; + nonverifiedcount=0; + rawDetails = new JSONArray(); + signatureDetails = new JSONArray(); + rawDetails.put(datatosign); + rawCount = 0; + loopCount =0; + + + + for (int i = 0; i < sizeofverifierpeers; i++) { + int j = i; + verifierThreads[i] = new Thread(() -> { + try { + //initiating threads to rest of the verifiers with appname = peerid+verifierdid +// PeerID.add(contractMembers.get(j).toString()); +// appName.add(PeerID.get(j).concat("verifierdid")); +// +// IPFSNetwork.swarmConnect(PeerID.get(j), ipfs); +// IPFSNetwork.forward(appName.get(j), SEND_PORT + j, PeerID.get(j)); + ContactNodesLogger.debug("Initiating Socket communication"); + senderSocket[j] = new Socket(contractMembers.get(j).toString(), SEND_PORT); + cin[j] = new BufferedReader(new InputStreamReader(senderSocket[j].getInputStream())); + cout[j] = new PrintStream(senderSocket[j].getOutputStream()); + + //Initiating request for data = did, peerid, wid, ip + ContactNodesLogger.debug("Sending REQ for Initializing connection with other verifiers"); + cout[j].println("REQ"); + + //TODO: If req is not received by other verifiers, they close the connection. + // But Verifier 1 - what to do? + + //get data from other verifiers + rawDataSync(new JSONObject(cin[j].readLine())); + + ContactNodesLogger.debug("Fetched raw data from other verifiers"); + + while (rawDetails.length() <= contractMembers.length()) {} + + ContactNodesLogger.debug("Raw details length: " + rawDetails.length()); + ContactNodesLogger.debug("RawCount: " + rawCount); + //send all the data collectively = IP and PeerID pair + ContactNodesLogger.debug("checking raw count and vip array length"); + + if (rawDetails.length() == (contractMembers.length()+1)) { + //checking the pairs + ContactNodesLogger.debug("checking raw count and raw details length"); + for (int k = 0; k < rawDetails.length(); k++) { + JSONObject rawObject = rawDetails.getJSONObject(k); + for (int l = 0; l < vipArray.length(); l++) { + JSONObject vipObject = vipArray.getJSONObject(l); + if (vipObject.getString("peerid").equals(rawObject.getString("peerid"))) { + if (vipObject.getString("ip").equals(rawObject.getString("ip"))) { + if (DIDFunctions.getRole(rawObject.getString("ip")).contains("Verifier")) + rawCount++; + } + } + loopCount++; + } + } + + while (loopCount < (vipArray.length() * rawDetails.length() * contractMembers.length())){} + + ContactNodesLogger.debug("IP-Peer Mappings Verified"); + ContactNodesLogger.debug("Raw Count: " + rawCount); + ContactNodesLogger.debug("loop Count: " + loopCount); + ContactNodesLogger.debug("Raw Details Length: " + rawDetails.length()); + ContactNodesLogger.debug("Raw Details: " + rawDetails); + + if ((rawCount/contractMembers.length()) == rawDetails.length()) { + ContactNodesLogger.debug("Sending Raw Details: " + rawDetails.toString()); + cout[j].println(rawDetails.toString()); + ContactNodesLogger.debug("Waiting for signatures"); + + signatureSync(new JSONObject(cin[j].readLine()), initiatordid, contractMembers); + + ContactNodesLogger.debug("Signatures Length: " + signatureDetails.length()); + ContactNodesLogger.debug("Contract Mem length: " + contractMembers.length()); + ContactNodesLogger.debug("Signatures : " + signatureDetails.toString()); + + while (signatureDetails.length() < contractMembers.length()) { + } + + JSONObject nodeSignObject = new JSONObject(); + nodeSignObject.put("did", signatureDetails.getJSONObject(j).getString("did")); + nodeSignObject.put("data", rawDetails); + String hash = calculateHash(nodeSignObject.toString(), "SHA3-256"); + ContactNodesLogger.debug("hash for verification : " + hash); + JSONObject verifyData = new JSONObject(); + ContactNodesLogger.debug(signatureDetails.getJSONObject(j).getString("did")); + verifyData.put("did", signatureDetails.getJSONObject(j).getString("did")); + verifyData.put("hash", hash); + verifyData.put("signature", signatureDetails.getJSONObject(j).getString("signature")); + ContactNodesLogger.debug("Verifying signatures"); + if (verifySignature(verifyData.toString())) + verifiedcount++; + else + nonverifiedcount++; + + ContactNodesLogger.debug("Verified Count" + verifiedcount); + ContactNodesLogger.debug("Non Verified Count" + nonverifiedcount); + + while (verifiedcount + nonverifiedcount < contractMembers.length()) { + } + if (nonverifiedcount == 0) { + ContactNodesLogger.debug("Sending ipfs hash of signatures list"); + cout[j].println(signatureDetails.toString()); + } + + } + //Sending Invalid Data if all verifiers does not respond with their data + else{ + cout[j].println("IP-PeerID mapping mismatch"); + ContactNodesLogger.debug("IP-PeerID mapping mismatch"); + nonverifiedcount++; + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + PeerID.get(j)); + + cout[j].close(); + cin[j].close(); + ContactNodesLogger.debug("Connection closed"); + } + } + //Sending Invalid Data if all verifiers does not respond with their data + else{ + cout[j].println("Invalid Raw data"); + ContactNodesLogger.debug("Raw data not received from all verifiers"); + nonverifiedcount++; + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + PeerID.get(j)); + + cout[j].close(); + cin[j].close(); + ContactNodesLogger.debug("Connection closed"); + } + + } catch (JSONException | IOException e) { + nonverifiedcount++; + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + PeerID.get(j)); + ContactNodesLogger.error("IO / JSON Exception", e); + cout[j].close(); + try { + cin[j].close(); + } catch (IOException ioException) { + ContactNodesLogger.error("IO Exception", ioException); + ioException.printStackTrace(); + } + ContactNodesLogger.debug("Connection closed"); + e.printStackTrace(); + } + }); + + verifierThreads[j].start(); + ContactNodesLogger.debug("Thread " + j + "Started"); + } + + while (verifiedcount + nonverifiedcount < contractMembers.length()){} + + ContactNodesLogger.debug("Verified Count: "+ verifiedcount); + ContactNodesLogger.debug("Signature details Count: "+ signatureDetails.length()); + if(verifiedcount == contractMembers.length() && signatureDetails.length() == contractMembers.length()+1) { + ContactNodesLogger.debug("true"); + writeToFile(DATA_PATH + "allsigndata.json", signatureDetails.toString(), false); + ContactNodesLogger.debug("All sign data is written into file - allsigndata.json"); + fileHash=add(DATA_PATH + "allsigndata.json", ipfs); + String dataTableFile = readFile(DATA_PATH + "DataTable.json"); + JSONArray dataTableArray = new JSONArray(dataTableFile); + + JSONArray newDataTableArray = new JSONArray(); + for(int l=0; l<dataTableArray.length(); l++){ + JSONObject dataTableObject = dataTableArray.getJSONObject(l); + dataTableObject.put("signHash", fileHash); + newDataTableArray.put(dataTableObject); + } + + ContactNodesLogger.debug("signHash - dataTable.json"); + writeToFile(DATA_PATH + "DataTable.json", newDataTableArray.toString() , false); + JSONArray newVipArray = new JSONArray(); + for (int k = 0; k < vipArray.length(); k++) { + JSONObject object = vipArray.getJSONObject(k); + object.put("status", "true"); + newVipArray.put(object); + } + ContactNodesLogger.debug("vip.json updated"); + writeToFile(DATA_PATH + "vip.json", newVipArray.toString(), false); + + return true; + } + else { + ContactNodesLogger.debug("false"); + return false; + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/DIDFunctions.java b/src/main/java/com/rubix/WAMPAC/DID/DIDFunctions.java new file mode 100644 index 0000000000000000000000000000000000000000..2dd0029d5e840e38df6af44a9bbee1ca6ca7f141 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/DIDFunctions.java @@ -0,0 +1,366 @@ +package com.rubix.WAMPAC.DID; + + +import com.rubix.Resources.Functions; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.*; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Timer; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.WAMPAC.NMS.Constants.PathConstants.*; + +public class DIDFunctions { + public static Logger DIDFunctionsLogger = Logger.getLogger(DIDFunctions.class); + public static boolean checkIPStatus() throws JSONException, UnknownHostException { + + String vipFile = readFile( "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + +// InetAddress myIP = InetAddress.getLocalHost(); +// String ip = myIP.getHostAddress(); +// System.out.println("IP Check" + ip); + + String ip = ipClass.getIP(); + System.out.println("/checkIpStatus IP Address: " + ip); + + for(int i = 0; i < vipArray.length(); i++){ + JSONObject object = vipArray.getJSONObject(i); + if(object.getString("ip").equals(ip)){ + if(object.getString("status").equals("false")){ + System.out.println("Status : " + object.getString("status")); + return true; + } + } + } + return false; + } +// public static boolean syncVip(String role) throws IOException, JSONException { +// PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); +// Functions.pathSet(); +// boolean syncFlag = false; +// StringBuilder result = new StringBuilder(); +// URL url = new URL(SYNC_IP + "/getvip"); +// 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 = true; +// } +// rd.close(); +// if(role.equals("Verifier")) +// writeToFile(DATA_PATH + "vip.json", result.toString(), false); +// else +// writeToFile("vip.json", result.toString(), false); +// return syncFlag; +// } + + public static void changePath() throws JSONException { + Functions.pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + File vip = new File("vip.json"); + String vipFile = readFile(vip.toString()); + JSONArray vipArray = new JSONArray(vipFile); + writeToFile(DATA_PATH + "vip.json", vipArray.toString(), false); + DIDFunctionsLogger.debug("vip.json File moved from current location"); + vip.delete(); + DIDFunctionsLogger.debug("vip.json File Deleted from current location"); + } + + public static String getRole(String ip) throws JSONException, IOException { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + File file = new File(DATA_PATH + "vip.json"); + if(file.exists()) { + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + + for (int i = 0; i < vipArray.length(); i++) { + JSONObject object = vipArray.getJSONObject(i); + if (object.getString("ip").equals(ip)) { + DIDFunctionsLogger.debug("role " + object.getString("role")); + return object.getString("role"); + } + } + } + return ""; + } + + + public static String verifierDID(String ip) throws JSONException, IOException { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + File file = new File(DATA_PATH + "vip.json"); + if(file.exists()) { + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + + //Check if already verified + for (int i = 0; i < vipArray.length(); i++) { + JSONObject vipArrayJSONObject = vipArray.getJSONObject(i); + if (vipArrayJSONObject.getString("ip").equals(ip)) { + if (vipArrayJSONObject.getString("status").equals("true")) + return "Success"; + } + } + + // Get all members peerid from vip.json + JSONArray contactMembers = new JSONArray(); + for (int i = 0; i < vipArray.length(); i++) { + JSONObject vipArrayJSONObject = vipArray.getJSONObject(i); + if (vipArrayJSONObject.getString("role").equals("Verifier") && !vipArrayJSONObject.getString("ip").equals(ip)) { + contactMembers.put(vipArrayJSONObject.getString("ip")); + } + } + DIDFunctionsLogger.debug("contact members" + contactMembers); + //Create data to send the other verifiers + String didFile = readFile(DATA_PATH + "DID.json"); + JSONArray didArray = new JSONArray(didFile); + JSONObject didObject = didArray.getJSONObject(0); + didObject.put("ip", ip); + + String mydid = didObject.getString("didHash"); + + //contactmembers is list of peerids to contact + // datatoquorum contain did,wid,peerid,ip of node - to be signed later + + DIDFunctionsLogger.debug("contacting contact members for verification"); + if (ContactNodes.contact(contactMembers, didObject, mydid)) + return "Success"; + else + return "Failure"; + } + else return "Failure"; + +// //Get all members from vip.json +// String vipFile = readFile(DATA_PATH + "vip.json"); +// JSONArray vipArray = new JSONArray(vipFile); +// +// JSONArray contactMembers = new JSONArray(); +// for(int i = 0; i < vipArray.length(); i++){ +// JSONObject object = vipArray.getJSONObject(i); +// if(object.getString("role").equals("Verifier") && !object.getString("ip").equals(ip)){ +// contactMembers.put(object.getString("peerid")); +// } +// } +// +// JSONObject dataToQuorum = new JSONObject(); +// +// //Create data to send the other verifiers +// String didFile = readFile(DATA_PATH + "DID.json"); +// JSONArray didArray = new JSONArray(didFile); +// JSONObject didObject = didArray.getJSONObject(0); +// didObject.put("ip", ip); +// dataToQuorum.put("data", didObject); +// +// //Contact all other verifiers +// int count = 0; +// String[] verifierCount = ContactNodes.contact(contactMembers, dataToQuorum); +// +// //TODO: resp - true r false +// //check the number of signatures verified +// if (verifierCount.length == contactMembers.length()) { +// for(int i=0; i< verifierCount.length; i++) { +// JSONObject object = new JSONObject(verifierCount[i]); +// if(object.get("count").equals(contactMembers.length())) +// count++; +// } +// } +// +// //if all verifiers count = 7, then change in the DataTable and Vip.json +// if (count == contactMembers.length()) { +// String dataTableFile = readFile(DATA_PATH + "DataTable.json"); +// JSONArray dataTableArray = new JSONArray(dataTableFile); +// JSONObject dataTableObject = dataTableArray.getJSONObject(0); +// dataTableObject.put("signHash", fileHash); +// writeToFile(DATA_PATH + "DataTable.json", new JSONArray().put(dataTableObject).toString(), false); +// JSONArray newVipArray = new JSONArray(); +// for(int k = 0; k < vipArray.length(); k++){ +// JSONObject vipObject = vipArray.getJSONObject(k); +// vipObject.put("status", true); +// newVipArray.put(vipObject); +// } +// writeToFile(DATA_PATH + "vip.json", newVipArray.toString(), false); +// return "Verifiers Agreed"; +// } +// //count doesnot match - exit +// else { +// return "Invalid Signatures"; +// } + } + + public static String userDID(String ip) throws JSONException, IOException { + pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + File file = new File(DATA_PATH + "vip.json"); + if(file.exists()) { + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + + // Get all members peerid from vip.json + + JSONArray contactMembers = new JSONArray(); + for (int i = 0; i < vipArray.length(); i++) { + JSONObject vipArrayJSONObject = vipArray.getJSONObject(i); + if (vipArrayJSONObject.getString("role").equals("Verifier") && !vipArrayJSONObject.getString("ip").equals(ip)) { + contactMembers.put(vipArrayJSONObject.getString("ip")); + } + } + DIDFunctionsLogger.debug("contact members" + contactMembers); + //Create data to send the other verifiers + String didFile = readFile(DATA_PATH + "DID.json"); + JSONArray didArray = new JSONArray(didFile); + JSONObject didObject = didArray.getJSONObject(0); + didObject.put("ip", ip); + DIDFunctionsLogger.debug("contacting contact members for verification"); + if (UserContactNodes.contact(contactMembers, didObject)) + return "Success"; + else + return "Failure"; + }else return "Failure"; + } + + public static int minVotes(int count) { + return (count - 1) / 3 * 2 + 1; + } + + public static boolean vipSync() throws IOException, JSONException { + pathSet(); + String url = "http://172.17.128.102:9090/getvip"; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // Setting basic get request + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", "Mozilla/5.0"); + 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(); + DIDFunctionsLogger.debug("Sending 'GET' request to URL : " + url + " for latest VIP"); + DIDFunctionsLogger.debug("Response Code : " + responseCode); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String response; + StringBuffer vipList = new StringBuffer(); + + while ((response = in.readLine()) != null) { + vipList.append(response); + } + in.close(); + DIDFunctionsLogger.debug("VIP List String buffer" + vipList.toString()); + + JSONArray vipArray = new JSONArray(vipList.toString()); + DIDFunctionsLogger.debug("VIP List JSON Array" + vipArray); + + if(vipArray != null){ + File vipFile = new File(DATA_PATH + "vip.json"); + if(!vipFile.exists()) + vipFile.createNewFile(); + + writeToFile(vipFile.toString(), vipArray.toString(), false); + return true; + } + else{ + return false; + } + } + + public static boolean rulesSync() throws IOException, JSONException { + pathSet(); + String url = "http://172.17.128.102:9090/getrules"; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // Setting basic get request + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", "Mozilla/5.0"); + 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(); + DIDFunctionsLogger.debug("Sending 'GET' request to URL : " + url + " for latest VIP"); + DIDFunctionsLogger.debug("Response Code : " + responseCode); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String response; + StringBuffer rulesList = new StringBuffer(); + + while ((response = in.readLine()) != null) { + rulesList.append(response); + } + in.close(); + DIDFunctionsLogger.debug("Rules List String buffer" + rulesList.toString()); + + JSONObject rulesObject = new JSONObject(rulesList.toString()); + DIDFunctionsLogger.debug("Rules List JSON Array" + rulesObject); + + pathSet(); + File nms = new File(nmsFolder); + if (!nms.exists()) + nms.mkdirs(); + + if(rulesObject != null){ + File rulesFile = new File(nmsFolder + "rules.json"); + if(!rulesFile.exists()) + rulesFile.createNewFile(); + + writeToFile(rulesFile.toString(), rulesObject.toString(), false); + return true; + } + else{ + return false; + } + } + + public static String macAddress(){ + String firstInterface = null; + HashMap<String, String> addressByNetwork = new HashMap<>(); + String MAC = ""; + Enumeration<NetworkInterface> networkInterfaces; + try { + networkInterfaces = NetworkInterface.getNetworkInterfaces(); + while (networkInterfaces.hasMoreElements()) { + NetworkInterface network = networkInterfaces.nextElement(); + + byte[] bmac = network.getHardwareAddress(); + if (bmac != null) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < bmac.length; i++) + sb.append(String.format("%02X%s", bmac[i], (i < bmac.length - 1) ? "-" : "")); + + if (!sb.toString().isEmpty()) + addressByNetwork.put(network.getName(), sb.toString()); + + if (!sb.toString().isEmpty() && firstInterface == null) + firstInterface = network.getName(); + } + } + } catch (SocketException e) { + DIDFunctionsLogger.error("Socket Exception Occurred", e); + e.printStackTrace(); + } + if (firstInterface != null) { + MAC = addressByNetwork.get(firstInterface); + DIDFunctionsLogger.debug("MAC Address : " + MAC); + } + return MAC; + } + +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/RequestTokens.java b/src/main/java/com/rubix/WAMPAC/DID/RequestTokens.java new file mode 100644 index 0000000000000000000000000000000000000000..7e5708959fbbc4113c67bca18ce951756f2263a5 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/RequestTokens.java @@ -0,0 +1,95 @@ +package com.rubix.WAMPAC.DID; + +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 java.io.*; +import java.net.*; + +import static com.rubix.Resources.Functions.*; + +public class RequestTokens { + public static Logger getTokensLogger = Logger.getLogger(RequestTokens.class); + private static final String USER_AGENT = "Mozilla/5.0"; + public static BufferedReader serverInput; + public static PrintStream serverOutput; + + public static String getTokens() { + String result = ""; + pathSet(); + IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + try { + String userUrl = "http://172.17.128.102:9090/gettokens"; + URL userObj = new URL(userUrl); + HttpURLConnection userCon = (HttpURLConnection) userObj.openConnection(); + + // Setting basic get request + userCon.setRequestMethod("GET"); + userCon.setRequestProperty("User-Agent", USER_AGENT); + userCon.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); + userCon.setRequestProperty("Accept", "application/json"); + userCon.setRequestProperty("Content-Type", "application/json"); + userCon.setRequestProperty("Authorization", "null"); + + serverInput = new BufferedReader(new InputStreamReader(userCon.getInputStream())); + String userResponse; + StringBuffer tokenList = new StringBuffer(); + + while ((userResponse = serverInput.readLine()) != null) { + tokenList.append(userResponse); + } + serverInput.close(); + + getTokensLogger.debug("Received tokenList from Server: " + tokenList); + JSONArray tokensArray = new JSONArray(tokenList.toString()); + if(tokensArray.length() > 0) { + File tokenListFile = new File(WALLET_DATA_PATH + "tokenList.json"); + if (!tokenListFile.exists()) { + tokenListFile.createNewFile(); + writeToFile(WALLET_DATA_PATH + "tokenList.json", String.valueOf(new JSONArray()), false); + } + String tokenListData = readFile(WALLET_DATA_PATH + "tokenList.json"); + JSONArray tokenListArray = new JSONArray(tokenListData); + + + for (int i = 0; i < tokensArray.length(); i++) { + String tokenHash = tokensArray.getString(i); + + String tokenIpfsGet = IPFSNetwork.get(tokenHash, ipfs); + System.out.println(tokenIpfsGet); + File tokenFile = new File(TOKENS_PATH + tokenHash); + tokenFile.createNewFile(); + writeToFile(TOKENS_PATH + tokenHash, tokenIpfsGet, false); + IPFSNetwork.add(Functions.TOKENS_PATH + tokenHash, ipfs); + + File tokenChainFile = new File(TOKENCHAIN_PATH + tokenHash + ".json"); + tokenChainFile.createNewFile(); + writeToFile(TOKENCHAIN_PATH + tokenHash + ".json", "[]", false); + IPFSNetwork.add(TOKENCHAIN_PATH + tokenHash + ".json", ipfs); + + JSONObject tokenObject = new JSONObject(); + tokenObject.put("tokenHash", tokenHash); + tokenListArray.put(tokenObject); + + getTokensLogger.debug("IPFS get Success: " + tokenHash); + + } + writeToFile(WALLET_DATA_PATH + "tokenList.json", tokenListArray.toString(), false); + result = "Success"; + }else + result = "Failure"; + + } catch (IOException | JSONException e) { + result = "Failure"; + e.printStackTrace(); + } + return result; + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/User/getDataFromVerifier.java b/src/main/java/com/rubix/WAMPAC/DID/User/getDataFromVerifier.java new file mode 100644 index 0000000000000000000000000000000000000000..d27c107482440745ddf23d6e7ab886fa8869423e --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/User/getDataFromVerifier.java @@ -0,0 +1,132 @@ +package com.rubix.WAMPAC.DID.User; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.Socket; +import java.net.URL; +import java.util.Random; + +import static com.rubix.Resources.Functions.*; + +public class getDataFromVerifier { + public static Logger getVerifierIpListLogger = Logger.getLogger(getDataFromVerifier.class); + private static final String USER_AGENT = "Mozilla/5.0"; + private static String result = ""; + public static Socket verifierServerSocket; + public static BufferedReader serverInput, input; + public static PrintStream output; + public static String getData() { + pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + try { + String userUrl = "http://172.17.128.102:9090/getverifiers"; + URL userObj = new URL(userUrl); + HttpURLConnection userCon = (HttpURLConnection) userObj.openConnection(); + + // Setting basic get request + userCon.setRequestMethod("GET"); + userCon.setRequestProperty("User-Agent", USER_AGENT); + userCon.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); + userCon.setRequestProperty("Accept", "application/json"); + userCon.setRequestProperty("Content-Type", "application/json"); + userCon.setRequestProperty("Authorization", "null"); + + serverInput = new BufferedReader(new InputStreamReader(userCon.getInputStream())); + String userResponse; + StringBuffer ipList = new StringBuffer(); + + while ((userResponse = serverInput.readLine()) != null) { + ipList.append(userResponse); + } + serverInput.close(); + JSONArray verifiersIpArray = new JSONArray(ipList.toString()); + + if(verifiersIpArray.length() > 0) { + + /** + * Contact one of the verifier + */ + Random rn = new Random(); + int index = rn.nextInt(verifiersIpArray.length()); + + getVerifierIpListLogger.debug("Connecting to verifier: " + verifiersIpArray.getString(index)); + verifierServerSocket = new Socket(verifiersIpArray.getString(index), 8787); + input = new BufferedReader(new InputStreamReader(verifierServerSocket.getInputStream())); + output = new PrintStream(verifierServerSocket.getOutputStream()); + + output.println("Request"); + + String incomingVipList; + getVerifierIpListLogger.debug("Waiting for vip.json"); + while ((incomingVipList = input.readLine()) == null) { + } + + JSONObject data = new JSONObject(incomingVipList); + JSONArray vipArray = data.getJSONArray("vip"); + JSONArray dataArray = data.getJSONArray("datatable"); + if (vipArray != null && dataArray != null) { + output.println("ACK"); + + + File vipFile = new File(DATA_PATH + "vip.json"); + if (!vipFile.exists()) + vipFile.createNewFile(); + writeToFile(DATA_PATH + "vip.json", vipArray.toString(), false); + + File dataTableFile = new File(DATA_PATH + "DataTable.json"); + if (!dataTableFile.exists()) + dataTableFile.createNewFile(); + writeToFile(DATA_PATH + "DataTable.json", dataArray.toString(), false); + + result = "Success"; + getVerifierIpListLogger.debug("Success"); + }else { + output.println("No-ACK"); + result = "Sync Failure. Try again"; + } + + serverInput.close(); + verifierServerSocket.close(); + input.close(); + output.close(); + + } + else{ + serverInput.close(); + verifierServerSocket.close(); + input.close(); + output.close(); + result = "Sync Failure. Try again"; + } + + } catch (IOException e) { + + result = "Sync Failure. Try again"; + getVerifierIpListLogger.error("IOException Occurred", e); + e.printStackTrace(); + + } catch (JSONException e) { + result = "Sync Failure. Try again"; + getVerifierIpListLogger.error("JSONException Occurred", e); + e.printStackTrace(); + + } finally { + try { + serverInput.close(); + verifierServerSocket.close(); + input.close(); + output.close(); + } catch (IOException e) { + e.printStackTrace(); + } + getVerifierIpListLogger.debug("Connection Closed"); + } + return result; + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/UserContactNodes.java b/src/main/java/com/rubix/WAMPAC/DID/UserContactNodes.java new file mode 100644 index 0000000000000000000000000000000000000000..ab0cde44dcd5461cc21104e02fabe1adee48309a --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/UserContactNodes.java @@ -0,0 +1,158 @@ +package com.rubix.WAMPAC.DID; + +import com.rubix.Resources.IPFSNetwork; +import io.ipfs.api.IPFS; +import org.apache.catalina.User; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; +import java.net.Socket; +import java.util.ArrayList; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.IPFSNetwork.add; +import static com.rubix.Resources.IPFSNetwork.executeIPFSCommands; +import static com.rubix.WAMPAC.DID.DIDFunctions.minVotes; + +public class UserContactNodes { + public static volatile JSONArray signatureDetails = new JSONArray(); + public static Logger UserContactNodesLogger = Logger.getLogger(UserContactNodes.class); + private static final Object signLock = new Object(); + public static String fileHash; + + public static synchronized void signatureSync(JSONObject data, JSONArray contractMembers){ + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + synchronized (signLock) { + if(signatureDetails.length() < minVotes(contractMembers.length())) + signatureDetails.put(data); + UserContactNodesLogger.debug("added to signature details in sync block: \n" + signatureDetails.toString()); + } + } + + public static boolean contact(JSONArray contractMembers, JSONObject userRawData) throws JSONException, IOException { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + int sizeofverifierpeers = contractMembers.length(); + PrintStream[] cout = new PrintStream[sizeofverifierpeers]; + BufferedReader[] cin = new BufferedReader[sizeofverifierpeers]; + Socket[] senderSocket = new Socket[sizeofverifierpeers]; + IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + ArrayList<String> PeerID = new ArrayList<>(); + ArrayList<String> appName = new ArrayList<>(); + + signatureDetails = new JSONArray(); + Thread[] verifierThreads = new Thread[contractMembers.length()]; + for (int i = 0; i < sizeofverifierpeers; i++) { + int j = i; + verifierThreads[i] = new Thread(() -> { + try { + //initiating threads to rest of the verifiers with appname = peerid+verifierdid + // PeerID.add(contractMembers.get(j).toString()); + // appName.add(PeerID.get(j).concat("verifieruserdid")); + + // IPFSNetwork.swarmConnect(PeerID.get(j), ipfs); + // IPFSNetwork.forward(appName.get(j), SEND_PORT + j, PeerID.get(j)); + UserContactNodesLogger.debug("Initiating socket communication"); + senderSocket[j] = new Socket(contractMembers.get(j).toString(), QUORUM_PORT); + cin[j] = new BufferedReader(new InputStreamReader(senderSocket[j].getInputStream())); + cout[j] = new PrintStream(senderSocket[j].getOutputStream()); + UserContactNodesLogger.debug("Sending raw data for initializing connection with other verifiers"); + cout[j].println(userRawData); + UserContactNodesLogger.debug("raw data: " + userRawData); + //Get Sign from verifiers + String response = cin[j].readLine(); + UserContactNodesLogger.debug("response from verifiers: " + response); + JSONObject responseObject = new JSONObject(response); + if (!responseObject.getString("status").contains("Invalid")) + signatureSync(responseObject, contractMembers); + + UserContactNodesLogger.debug("Fetched signatures from other verifiers: \n" + signatureDetails.toString()); + while (signatureDetails.length() < minVotes(contractMembers.length())) { + } + + UserContactNodesLogger.debug("Signatures length" + signatureDetails.length()); + + UserContactNodesLogger.debug("Contract members length" + contractMembers.length()); + + UserContactNodesLogger.debug("Minimum Votes" + minVotes(contractMembers.length())); + + if(signatureDetails.length() == minVotes(contractMembers.length())) { + UserContactNodesLogger.debug("Sending signs to thread: " + j); + cout[j].println(signatureDetails.toString()); + } + + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + PeerID.get(j)); + cout[j].close(); + cin[j].close(); + UserContactNodesLogger.debug("Connection Closed after success"); + + } catch (JSONException | IOException e) { + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + PeerID.get(j)); + UserContactNodesLogger.error("IO / JSON Exception", e); + cout[j].close(); + try { + cin[j].close(); + } catch (IOException ioException) { + UserContactNodesLogger.error("IO Exception", ioException); + ioException.printStackTrace(); + } + UserContactNodesLogger.debug("Connection Closed"); + e.printStackTrace(); + } + }); + + verifierThreads[j].start(); + UserContactNodesLogger.debug("Thread " + j + "Started"); + } + while (signatureDetails.length() < minVotes(contractMembers.length())) { + } + UserContactNodesLogger.debug("Minimum votes req: "+ minVotes(contractMembers.length())); + UserContactNodesLogger.debug("Signature details Count: "+ signatureDetails.length()); + + if (signatureDetails.length()== minVotes(contractMembers.length())) { + + File signaturesFile = new File(DATA_PATH + "VerifiedDidSignatures.json"); + if (!signaturesFile.exists()) + signaturesFile.createNewFile(); + UserContactNodesLogger.debug("All sign data is written into file - VerifiedDidSignatures.json"); + writeToFile(signaturesFile.toString(), signatureDetails.toString(), false); + UserContactNodesLogger.debug("pushing signatures into ipfs"); + fileHash = add(signaturesFile.toString(), ipfs); + + + String dataTableFile = readFile(DATA_PATH + "DataTable.json"); + JSONArray dataTableArray = new JSONArray(dataTableFile); + JSONArray newDataTableArray = new JSONArray(); + for (int l = 0; l < dataTableArray.length(); l++) { + JSONObject dataTableObject = dataTableArray.getJSONObject(l); + if (dataTableObject.getString("peerid").equals(userRawData.getString("peerid"))) + dataTableObject.put("signHash", fileHash); + newDataTableArray.put(dataTableObject); + } + + UserContactNodesLogger.debug("signHash of user - dataTable.json"); + writeToFile(DATA_PATH + "DataTable.json", newDataTableArray.toString(), false); + + for (int l = 0; l < vipArray.length(); l++) { + JSONObject userObject = vipArray.getJSONObject(l); + if (userObject.getString("peerid").equals(userRawData.getString("peerid"))) { + userObject.put("status", "true"); + vipArray.remove(l); + vipArray.put(userObject); + } + } + UserContactNodesLogger.debug("Updating vip.json"); + writeToFile(DATA_PATH + "vip.json", vipArray.toString(), false); + + return true; + } + else{ + return false; + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/Verifier/Details.java b/src/main/java/com/rubix/WAMPAC/DID/Verifier/Details.java new file mode 100644 index 0000000000000000000000000000000000000000..f80f6608bdada0896014cce093e1fc170ea8476e --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/Verifier/Details.java @@ -0,0 +1,29 @@ +package com.rubix.WAMPAC.DID.Verifier; + + +public class Details { + + private String peerid; + private String role; + private String ip; + private String status; + + private String didHash; + private String walletHash; + + + + + + public Details(){} + + public String getPeerid(){return peerid;} + public String getRole(){return role;} + public String getIp(){ return ip;} + public String getStatus(){return status;} + + public String getDidHash(){ return didHash;} + public String getWalletHash(){return walletHash;} + + +} \ No newline at end of file diff --git a/src/main/java/com/rubix/WAMPAC/DID/Verifier/addUserDataTableListen.java b/src/main/java/com/rubix/WAMPAC/DID/Verifier/addUserDataTableListen.java new file mode 100644 index 0000000000000000000000000000000000000000..d74a91524105e5ed46a33553a5659e38a7a07098 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/Verifier/addUserDataTableListen.java @@ -0,0 +1,61 @@ +package com.rubix.WAMPAC.DID.Verifier; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; + +import static com.rubix.Resources.Functions.*; + +public class addUserDataTableListen { + + public static Logger addUserDataTableListenLogger = Logger.getLogger(addUserDataTableListen.class); + public static String result = ""; + public static String listen(JSONObject userRawData) { + setDir(); + setConfig(); + File didFolder = new File(configPath); + if (!didFolder.exists()) + return "No DID"; + + pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + try { + String newDid = userRawData.getString("didHash"); + + File vipFileCon = new File(DATA_PATH + "vip.json"); + if(!vipFileCon.exists()) + return "No VIP File"; + + String dataFile = readFile(DATA_PATH + "DataTable.json"); + JSONArray dataTableList = new JSONArray(dataFile); + boolean flag = false; + int index = 0; + for(int i = 0; i < dataTableList.length(); i++){ + if(dataTableList.getJSONObject(i).getString("didHash").equals(newDid)) { + flag = true; + index = i; + } + } + if(flag) + dataTableList.remove(index); + + dataTableList.put(userRawData); + writeToFile(DATA_PATH + "DataTable.json", dataTableList.toString(), false); + + + } catch (JSONException e) { + result = "IOException Occurred" + e; + addUserDataTableListenLogger.error("JSONException Occurred", e); + e.printStackTrace(); + addUserDataTableListenLogger.debug("Connection Closed"); + + + } + return result; + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/Verifier/addUserVipListen.java b/src/main/java/com/rubix/WAMPAC/DID/Verifier/addUserVipListen.java new file mode 100644 index 0000000000000000000000000000000000000000..e75bbabbb5dfec7907c232a9f453f014a2efda53 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/Verifier/addUserVipListen.java @@ -0,0 +1,62 @@ +package com.rubix.WAMPAC.DID.Verifier; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; + +import static com.rubix.Resources.Functions.*; + +public class addUserVipListen { + + public static Logger addUserVipListenLogger = Logger.getLogger(addUserVipListen.class); + public static String result = ""; + public static String listen(JSONObject userRawData) { + + setDir(); + setConfig(); + + File didFolder = new File(configPath); + if (!didFolder.exists()) + return "No DID"; + + pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + try { + + String newIp = userRawData.getString("ip"); + File vipFileCon = new File(DATA_PATH + "vip.json"); + if (!vipFileCon.exists()) + return "No VIP File"; + + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + + boolean flag = false; + int index = 0; + for(int i = 0; i < vipArray.length(); i++){ + if(vipArray.getJSONObject(i).getString("ip").equals(newIp)) { + flag = true; + index = i; + } + } + if(flag) + vipArray.remove(index); + + vipArray.put(userRawData); + writeToFile(DATA_PATH + "vip.json", vipArray.toString(), false); + + result = "User Added To Vip"; + + } catch (JSONException e) { + result = "IOException Occurred" + e; + addUserVipListenLogger.error("JSONException Occurred ", e); + e.printStackTrace(); + addUserVipListenLogger.debug("Connection Closed"); + } + return result; + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/Verifier/sendToUser.java b/src/main/java/com/rubix/WAMPAC/DID/Verifier/sendToUser.java new file mode 100644 index 0000000000000000000000000000000000000000..3389b1bbe4667077d0c0ed4bcd743e8f0f5ede68 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/Verifier/sendToUser.java @@ -0,0 +1,114 @@ +package com.rubix.WAMPAC.DID.Verifier; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.ServerSocket; +import java.net.Socket; + +import static com.rubix.Resources.Functions.*; + +public class sendToUser implements Runnable{ + public static Logger sendVipToUserLogger = Logger.getLogger(sendToUser.class); + public static ServerSocket serverSocket = null; + public static Socket socket = null; + public static BufferedReader in; + public static PrintStream out; + + + @Override + public void run() { + while (true) { + System.out.println("Listening for user data request ..."); + pathSet(); + String result = ""; + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + try { + + serverSocket = new ServerSocket(8787); + socket = serverSocket.accept(); + sendVipToUserLogger.debug("Verifier Listening on " + 8787 + " for user's request of Vip list"); + + in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + out = new PrintStream(socket.getOutputStream()); + + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + + String dataTableFile = readFile(DATA_PATH + "DataTable.json"); + JSONArray dataTableArray = new JSONArray(dataTableFile); + + JSONObject data = new JSONObject(); + data.put("vip", vipArray); + data.put("datatable", dataTableArray); + String incomingRequest; + sendVipToUserLogger.debug("Waiting for Request from User"); + while ((incomingRequest = in.readLine()) == null) { + } + + if (incomingRequest.contains("Request")) { + out.println(data.toString()); + + while ((incomingRequest = in.readLine()) == null) { + } + + if (incomingRequest.contains("ACK")) { + result = "Data Sent"; + System.out.println(result); + sendVipToUserLogger.debug("Details Acknowledged"); + } else { + result = "Data Sent but user not ack"; + System.out.println(result); + sendVipToUserLogger.debug("Details Not Acknowledged"); + } + }else { + result = "Bad Request"; + System.out.println(result); + sendVipToUserLogger.debug("Details Not Acknowledged"); + } + + serverSocket.close(); + socket.close(); + in.close(); + out.close(); + + } catch (IOException e) { + result = "IOException Occurred" + e; + System.out.println(result); + sendVipToUserLogger.error("IOException Occurred", e); + e.printStackTrace(); + sendVipToUserLogger.debug("Connection Closed"); + + } catch (JSONException e) { + result = "IOException Occurred" + e; + System.out.println(result); + sendVipToUserLogger.error("JSONException Occurred", e); + e.printStackTrace(); + sendVipToUserLogger.debug("Connection Closed"); + + + } finally { + try { + socket.close(); + serverSocket.close(); + sendVipToUserLogger.debug("Connection Closed"); + } catch (IOException e) { + + result = "IOException Occurred" + e; + System.out.println(result); + sendVipToUserLogger.error("IOException Occurred", e); + e.printStackTrace(); + } + } + System.out.println(result); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/VerifierListen.java b/src/main/java/com/rubix/WAMPAC/DID/VerifierListen.java new file mode 100644 index 0000000000000000000000000000000000000000..56d8fb51c6a359fd482b32cc1338f1da38d2ca73 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/VerifierListen.java @@ -0,0 +1,267 @@ +package com.rubix.WAMPAC.DID; + +import com.rubix.Resources.IPFSNetwork; +import io.ipfs.api.IPFS; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; + +import static com.rubix.AuthenticateNode.Authenticate.verifySignature; +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.IPFSNetwork.*; + +public class VerifierListen implements Runnable { + + + public static Logger VerifierLogger = Logger.getLogger(VerifierListen.class); + + /** + * This method is used to run a thread for Quorum Members + * <p>This involves <ol> <li>Verify sender signature</li> + * <li>Signing the transaction</li> + * <li>Receiving share from sender</li></ol> + */ + public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + + @Override + public void run() { + while (true) { + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + String peerID, appName, senderPID = ""; + ServerSocket serverSocket = null; + Socket socket = null; + try { + + //listening on QUORUM_PORT & APPNAME = Peerid+verifierdid + + + // peerID = getPeerID(DATA_PATH + "DID.json"); + // appName = peerID.concat("verifierdid"); + + // IPFSNetwork.listen(appName, QUORUM_PORT); + + + VerifierLogger.debug("Verifier Listening on " + SEND_PORT); + serverSocket = new ServerSocket(SEND_PORT); + socket = serverSocket.accept(); + + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + PrintStream out = new PrintStream(socket.getOutputStream()); + + //Sending data = did, peerid, wid, ip : jsonobject + + String didFile = readFile(DATA_PATH + "DID.json"); +// InetAddress myIP = InetAddress.getLocalHost(); +// String ip = myIP.getHostAddress(); +// VerifierLogger.debug("Verifier IP " + ip); + + String ip = ipClass.getIP(); + System.out.println("Verifier IP: " + ip); + + JSONArray didArray = new JSONArray(didFile); + JSONObject didObject = didArray.getJSONObject(0); + didObject.put("ip", ip); + + + String incomingCode; + VerifierLogger.debug("Verifier waiting for initiate request from verifier 1"); + while ((incomingCode = in.readLine()) == null) { + } + VerifierLogger.debug("Incoming code" + incomingCode); + if (incomingCode.equals("REQ")) { + + out.println(didObject); + VerifierLogger.debug("sent object for IP an PeerID verification" + didObject); + VerifierLogger.debug("Waiting for IP PeerID collective list"); + String getData; + while ((getData = in.readLine()) == null) { + } + VerifierLogger.debug("data received : " + getData); + //received data(IP, Peerid) and checking whether it is valid or invalid + //Invalid - when 7 members data is not obtained + if (!getData.contains("IP-PeerID mapping mismatch")) { + VerifierLogger.debug("Received Details from Verifier 1: " + getData); + int rawCount = 0; + JSONArray rawDetails = new JSONArray(getData); + + //read vip.json and check the IP PeerID mapping from the data received + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + for (int k = 0; k < rawDetails.length(); k++) { + JSONObject rawObject = rawDetails.getJSONObject(k); + for (int l = 0; l < vipArray.length(); l++) { + JSONObject vipObject = vipArray.getJSONObject(l); + if (vipObject.getString("peerid").equals(rawObject.getString("peerid"))) + if (vipObject.getString("ip").equals(rawObject.getString("ip"))) + if (DIDFunctions.getRole(rawObject.getString("ip")).contains("Verifier")) + rawCount++; + } + } + + VerifierLogger.debug("Mapping verified"); + // If mapping is correct, send the signature on the IP-PeerID mapping list + JSONObject signObject = new JSONObject(); + signObject.put("did", didObject.getString("didHash")); + signObject.put("data", rawDetails); + String mySign = sign(signObject.toString()); + VerifierLogger.debug("Raw count: " + rawCount); + VerifierLogger.debug("Raw Details Length: " + rawDetails.length()); + VerifierLogger.debug("Raw Details : " + rawDetails); + + if (rawCount == rawDetails.length()) { + JSONObject responseObject = new JSONObject(); + responseObject.put("did", didObject.getString("didHash")); + responseObject.put("signature", mySign); + responseObject.put("status", "Verifiers Matched"); + VerifierLogger.debug("Sending Signature" + responseObject.toString()); + out.println(responseObject.toString()); + + VerifierLogger.debug("Waiting for IPFS Hash of Signatures List"); + String signDetails; + while ((signDetails = in.readLine()) == null) { + } + //fetch the hash from IPFS + VerifierLogger.debug("Signature Details" + signDetails); +// String getHash = get(ipfsSignHash, ipfs); + JSONArray signatureArray = new JSONArray(signDetails); + int verifyCount = 0; + + VerifierLogger.debug("verifying all the received signatures"); + //verify all the received signatures + for (int i = 0; i < signatureArray.length(); i++) { + JSONObject nodeSignObject = new JSONObject(); + nodeSignObject.put("did", signatureArray.getJSONObject(i).getString("did")); + nodeSignObject.put("data", rawDetails); + String hash = calculateHash(nodeSignObject.toString(), "SHA3-256"); + VerifierLogger.debug("hash for verification : " + hash); + JSONObject verifyData = new JSONObject(); + verifyData.put("did", signatureArray.getJSONObject(i).getString("did")); + verifyData.put("hash", hash); + verifyData.put("signature", signatureArray.getJSONObject(i).getString("signature")); + if (verifySignature(verifyData.toString())) { + verifyCount++; + } + } + //send the number of signatures verified to verifier 1 +// JSONObject signatureResponseObject = new JSONObject(); +// signatureResponseObject.put("count", verifyCount); +// out.println(signatureResponseObject.toString()); + + //if count = 7, then write into table and vip.json + VerifierLogger.debug("Verification count : " + verifyCount); + if (verifyCount == signatureArray.length()) { + writeToFile(DATA_PATH + "allsigndata.json", signatureArray.toString(), false); + VerifierLogger.debug("All sign data is written into file - allsigndata.json"); + String fileHash=add(DATA_PATH + "allsigndata.json", ipfs); + + String dataTableFile = readFile(DATA_PATH + "DataTable.json"); + JSONArray dataTableArray = new JSONArray(dataTableFile); + JSONArray newDataTableArray = new JSONArray(); + for (int l = 0; l < dataTableArray.length(); l++) { + JSONObject dataTableObject = dataTableArray.getJSONObject(l); + dataTableObject.put("signHash", fileHash); + newDataTableArray.put(dataTableObject); + } + + VerifierLogger.debug("signHash - dataTable.json"); + writeToFile(DATA_PATH + "DataTable.json", newDataTableArray.toString(), false); + + JSONArray newVipArray = new JSONArray(); + for (int k = 0; k < vipArray.length(); k++) { + JSONObject object = vipArray.getJSONObject(k); + object.put("status", "true"); + newVipArray.put(object); + } + VerifierLogger.debug("Status - vip.json"); + writeToFile(DATA_PATH + "vip.json", newVipArray.toString(), false); + } + //count not equal to 7 - exit + else { + VerifierLogger.debug("Invalid Signatures"); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + + socket.close(); + serverSocket.close(); + VerifierLogger.debug("Connection closed"); + VerifierLogger.debug("Invalid Signatures"); + } + } + //if IP-PeerID mapping fails, send empty signatures + else { + JSONObject responseObject = new JSONObject(); + responseObject.put("did", didObject.getString("did")); + responseObject.put("signature", ""); + responseObject.put("status", "Verifiers doesnot Match"); + out.println(responseObject); + VerifierLogger.debug("IP-PeerID mapping mismatch"); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + + socket.close(); + serverSocket.close(); + VerifierLogger.debug("Connection closed"); + VerifierLogger.debug("Verifiers does not Match"); + } + } + //when 7 members data is not sent to verifier 1 + else { + VerifierLogger.debug("Invalid Raw Data"); + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + socket.close(); + serverSocket.close(); + VerifierLogger.debug("Connection closed"); + + VerifierLogger.debug("Invalid Raw Data"); + } + out.close(); + in.close(); + socket.close(); + serverSocket.close(); + } + //if REQ is not sent by Verifier 1 + else { + VerifierLogger.debug("REQ not sent by Verifier"); + //executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + + out.close(); + in.close(); + socket.close(); + serverSocket.close(); + VerifierLogger.debug("Connection closed"); + VerifierLogger.debug("Invalid Request"); + } + + } catch (IOException e) { + //executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + VerifierLogger.debug("Connection closed"); + VerifierLogger.error("IOException Occurred", e); + e.printStackTrace(); + } catch (JSONException e) { + //executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + VerifierLogger.debug("Connection closed"); + VerifierLogger.error("JSONException Occurred", e); + e.printStackTrace(); + } finally { + try { + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + + socket.close(); + serverSocket.close(); + VerifierLogger.debug("Connection closed"); + } catch (IOException e) { + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + + VerifierLogger.debug("Connection closed"); + VerifierLogger.error("IOException Occurred", e); + e.printStackTrace(); + } + } + VerifierLogger.debug("Verifiers Agreed"); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/VerifierUserListen.java b/src/main/java/com/rubix/WAMPAC/DID/VerifierUserListen.java new file mode 100644 index 0000000000000000000000000000000000000000..457d2c0cdb4f88d39381f2388d7bebb5b58ff350 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/VerifierUserListen.java @@ -0,0 +1,175 @@ +package com.rubix.WAMPAC.DID; + +import com.rubix.Resources.IPFSNetwork; +import io.ipfs.api.IPFS; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.Resources.IPFSNetwork.*; + +public class VerifierUserListen implements Runnable { + + public static Logger VerifierUserLogger = Logger.getLogger(VerifierUserListen.class); + public static IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + + @Override + public void run() { + while(true) { + pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + String peerID, appName, senderPID = ""; + ServerSocket serverSocket = null; + Socket socket = null; + try { + + //listening on QUORUM_PORT & APPNAME = Peerid+verifierdid +// peerID = getPeerID(DATA_PATH + "DID.json"); +// appName = peerID.concat("verifieruserdid"); + + // IPFSNetwork.listen(appName, QUORUM_PORT); + + + VerifierUserLogger.debug("Verifier Listening on " + QUORUM_PORT); + serverSocket = new ServerSocket(QUORUM_PORT); + socket = serverSocket.accept(); + + + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + PrintStream out = new PrintStream(socket.getOutputStream()); + + String didFile = readFile(DATA_PATH + "DID.json"); + JSONArray didArray = new JSONArray(didFile); + JSONObject didObject = didArray.getJSONObject(0); + String verifierDid = didObject.getString("didHash"); + + String incomingRawData; + + VerifierUserLogger.debug("Waiting for IP-Peer Pairs"); + while ((incomingRawData = in.readLine()) == null) { + } + VerifierUserLogger.debug("IP-Peer Pairs: " + incomingRawData); + VerifierUserLogger.debug("Verifying pairs"); + JSONObject userRawData = new JSONObject(incomingRawData); + // senderPID = userRawData.getString("peerid"); + String vipFile = readFile(DATA_PATH + "vip.json"); + JSONArray vipArray = new JSONArray(vipFile); + boolean userMapped = false; + for (int l = 0; l < vipArray.length(); l++) { + JSONObject vipObject = vipArray.getJSONObject(l); + if (vipObject.getString("peerid").equals(userRawData.getString("peerid"))) + if (vipObject.getString("ip").equals(userRawData.getString("ip"))) + if (vipObject.getString("status").equals("false")) + userMapped = true; + + } + VerifierUserLogger.debug("Mapping status: " + userMapped); + if (userMapped) { + VerifierUserLogger.debug("IP_pair of user mapped"); + JSONObject signObject = new JSONObject(); + signObject.put("did", verifierDid); + signObject.put("data", userRawData); + String mySign = sign(signObject.toString()); + + JSONObject responseObject = new JSONObject(); + responseObject.put("did", verifierDid); + responseObject.put("signature", mySign); + responseObject.put("status", "Valid IP - Peer Mapping"); + out.println(responseObject.toString()); + VerifierUserLogger.debug("Sending sign to user: " + responseObject.toString()); + + VerifierUserLogger.debug("Waiting for IPFS Hash of Signatures List"); + String signatures; + while ((signatures = in.readLine()) == null) { + } + //fetch the hash from IPFS + VerifierUserLogger.debug("ipfs hash" + signatures); + JSONArray signsArray = new JSONArray(signatures); + + for (int l = 0; l < vipArray.length(); l++) { + JSONObject userObject = vipArray.getJSONObject(l); + if (userObject.getString("peerid").equals(userRawData.getString("peerid"))) { + userObject.put("status", "true"); + vipArray.remove(l); + vipArray.put(userObject); + } + } + VerifierUserLogger.debug("Updating vip.json"); + writeToFile(DATA_PATH + "vip.json", vipArray.toString(), false); + + File signaturesFile = new File(DATA_PATH + "VerifiedDidSignatures.json"); + if (!signaturesFile.exists()) + signaturesFile.createNewFile(); + VerifierUserLogger.debug("All sign data is written into file - VerifiedDidSignatures.json"); + writeToFile(signaturesFile.toString(), signsArray.toString(), false); + VerifierUserLogger.debug("pushing signatures into ipfs"); + String fileHash = add(signaturesFile.toString(), ipfs); + + String dataTableFile = readFile(DATA_PATH + "DataTable.json"); + JSONArray dataTableArray = new JSONArray(dataTableFile); + JSONArray newDataTableArray = new JSONArray(); + for (int l = 0; l < dataTableArray.length(); l++) { + JSONObject dataTableObject = dataTableArray.getJSONObject(l); + if (dataTableObject.getString("peerid").equals(userRawData.getString("peerid"))) + dataTableObject.put("signHash", fileHash); + newDataTableArray.put(dataTableObject); + } + + VerifierUserLogger.debug("signHash of user - dataTable.json"); + writeToFile(DATA_PATH + "DataTable.json", newDataTableArray.toString(), false); + + out.close(); + in.close(); + socket.close(); + serverSocket.close(); + + } else { + JSONObject responseObject = new JSONObject(); + responseObject.put("did", verifierDid); + responseObject.put("signature", ""); + responseObject.put("status", "Invalid IP - Peer Mapping"); + out.println(responseObject.toString()); + VerifierUserLogger.debug("Sending status to user: " + responseObject.toString()); + out.close(); + in.close(); + socket.close(); + serverSocket.close(); + VerifierUserLogger.debug("Invalid IP - Peer Mapping"); + VerifierUserLogger.debug("Connection Closed"); + } + } catch (IOException e) { + //executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + VerifierUserLogger.error("IOException Occurred", e); + e.printStackTrace(); + VerifierUserLogger.debug("Connection Closed"); + + } catch (JSONException e) { + //executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + VerifierUserLogger.error("JSONException Occurred", e); + e.printStackTrace(); + VerifierUserLogger.debug("Connection Closed"); + + + } finally { + try { + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + socket.close(); + serverSocket.close(); + VerifierUserLogger.debug("Connection Closed"); + } catch (IOException e) { + // executeIPFSCommands(" ipfs p2p close -t /p2p/" + senderPID); + VerifierUserLogger.error("IOException Occurred", e); + e.printStackTrace(); + } + } + VerifierUserLogger.debug("User Verified"); + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/DID/ipClass.java b/src/main/java/com/rubix/WAMPAC/DID/ipClass.java new file mode 100644 index 0000000000000000000000000000000000000000..9591b779e71f4833adb953d43cc81d9a812852f8 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/DID/ipClass.java @@ -0,0 +1,30 @@ +package com.rubix.WAMPAC.DID; + +import java.net.*; +import java.util.Collections; +import java.util.Enumeration; + +public class ipClass { + public static String getIP() { + String myIP = ""; + try { + Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces.hasMoreElements()) { + NetworkInterface iface = interfaces.nextElement(); + if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) + continue; + Enumeration<InetAddress> addresses = iface.getInetAddresses(); + while(addresses.hasMoreElements()) { + InetAddress address = addresses.nextElement(); + final String ip = address.getHostAddress(); + if(Inet4Address.class == address.getClass() && !ip.contains("127.0.0.1")) + myIP = ip; + } + } + } catch (SocketException e) { + myIP = "Error: " + e; + } + return myIP; + } +} + diff --git a/src/main/java/com/rubix/WAMPAC/FileAccess/FileAccessFunctions.java b/src/main/java/com/rubix/WAMPAC/FileAccess/FileAccessFunctions.java new file mode 100644 index 0000000000000000000000000000000000000000..d9873cb33745552c85f8647b379d9902c45d0c86 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/FileAccess/FileAccessFunctions.java @@ -0,0 +1,367 @@ +package com.rubix.WAMPAC.FileAccess; + +import com.rubix.Resources.Functions; +import com.rubix.WAMPAC.DID.ipClass; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.*; +import java.net.InetAddress; +import java.net.Socket; +import java.util.ArrayList; + +import static com.rubix.AuthenticateNode.Authenticate.verifySignature; +import static com.rubix.Resources.Functions.*; + +public class FileAccessFunctions { + public static Logger FileAccessFunctionsLogger = Logger.getLogger(FileAccessFunctions.class); + public static volatile JSONArray SignatureDetails = new JSONArray(); + public static volatile int noverify,selfverify, valid, error, signatureStatus, verifiedStatus, nonVerifiedStatus = 0; + private static final Object signLock = new Object(); + public static volatile boolean verstatus, launchStatus= false; + public static String DRIVE_PATH=""; + + public static synchronized void signatureSync(JSONObject data){ + Functions.pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + synchronized (signLock) { + SignatureDetails.put(data); + FileAccessFunctionsLogger.debug("Added signature details in sync block. Length : " +SignatureDetails.length()); + } + } + + public static boolean verifyWriteCount(String did, JSONArray contractData, String ip) throws JSONException { + + Functions.pathSet(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + FileAccessFunctionsLogger.debug("Verifying write count"); + if(contractData.length() == 0) + return false; + int oldval = 0; + for (int i = 0; i < contractData.length(); i++) { + String id = contractData.getJSONObject(i).getString("did"); + String ipfetch = contractData.getJSONObject(i).getString("ip"); + if (id.equals(did) && ipfetch.equals(ip)) { + oldval = contractData.getJSONObject(i).getInt("writeCount"); + } + } + FileAccessFunctionsLogger.debug("Current writeCount: " + oldval); + FileAccessFunctionsLogger.debug("DID: " + did); + + if (oldval > 0) + return true; + else + return false; + } + + public static void createRbxDrive() { + pathSet(); + System.out.println(getOsName()); + if (getOsName().contains("Windows")) + DRIVE_PATH = "C:\\Rubix\\Wallet\\RubixDrive\\"; + else if (getOsName().contains("Mac")) + DRIVE_PATH = "/Applications/Rubix/Wallet/RubixDrive/"; + else + DRIVE_PATH = "/home/" + getSystemUser() + "/Rubix/Wallet/RubixDrive/"; + System.out.println("Drive path" + DRIVE_PATH); + File driveFolder = new File(DRIVE_PATH); + if (!driveFolder.exists()) { + driveFolder.mkdirs(); + } + } + + public static void updateContract(String did, String newFileHash, String token) throws JSONException, IOException, InterruptedException { + + Functions.pathSet(); + createRbxDrive(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + FileAccessFunctionsLogger.debug("Updating contract File values"); + String contractFile = readFile(DRIVE_PATH + "Contracts.json"); + JSONArray contractArray = new JSONArray(contractFile); + for (int i = 0; i < contractArray.length(); i++) { + JSONObject innerObject = contractArray.getJSONObject(i); + if (innerObject.getString("token").equals(token)) { + JSONArray contractData = innerObject.getJSONArray("contractData"); + for(int j=0; j< contractData.length(); j++) { + if (contractData.getJSONObject(j).getString("did").equals(did)) { + int oldVal = contractData.getJSONObject(j).getInt("writeCount"); + contractData.getJSONObject(j).put("writeCount", oldVal - 1); + innerObject.put("contractData", contractData); + innerObject.put("fileHash", newFileHash); + innerObject.put("status", true); + } + } + contractArray.remove(i); + contractArray.put(innerObject); + FileAccessFunctionsLogger.debug("Current contract data" + contractArray.toString()); + writeToFile(DRIVE_PATH + "Contracts.json", contractArray.toString(), false); + } + } + } + public static boolean signInitiator(String token, JSONObject hashObject, String operation, String filename) throws JSONException, IOException, InterruptedException { + Functions.pathSet(); + createRbxDrive(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + signatureStatus = 0; + verifiedStatus = 0; + valid = 0; + error = 0; + selfverify = 0; + noverify=0; + SignatureDetails = new JSONArray(); + FileAccessFunctionsLogger.debug("Reset signatureStatus, verifiedStatus and SignatureDetails"); + //set signatureStatus = true + //IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + //JSONObject- contractdata - get other verifiers except mydid – ContractMem + JSONObject signObject = new JSONObject(); + signObject.put("did", hashObject.getString("did")); + signObject.put("data", token + hashObject); + String sign = Functions.sign(signObject.toString()); + FileAccessFunctionsLogger.debug("Initiator Sign on JSONObject: " +sign); + + String did = hashObject.getString("did"); + ArrayList<String> resultString = new ArrayList<>(); + JSONArray contractData = hashObject.getJSONArray("contractData"); + FileAccessFunctionsLogger.debug("Contract Data in SignInit Start:" + contractData); + +// InetAddress myIP = InetAddress.getLocalHost(); +// String ip = myIP.getHostAddress(); +// FileAccessFunctionsLogger.debug("my IP" + ip); + + String myIp = ipClass.getIP(); + System.out.println("/signInitiator IP Address: " + myIp); + + for (int i = 0; i < contractData.length(); i++) { + String fetchIp = contractData.getJSONObject(i).getString("ip"); + if (!fetchIp.contains(myIp)) + resultString.add(fetchIp); + } + FileAccessFunctionsLogger.debug("Fetched contract Members to contact" + resultString.size()); + + PrintStream[] cout = new PrintStream[resultString.size()]; + BufferedReader[] cin = new BufferedReader[resultString.size()]; + Socket[] senderSocket = new Socket[resultString.size()]; + + JSONObject dataVerify = new JSONObject(); + dataVerify.put("signature", sign); + dataVerify.put("data", hashObject); + signatureSync(dataVerify); + FileAccessFunctionsLogger.debug("Added Init signature details"); + dataVerify.put("token", token); + + //Forward to ContractMem + Thread[] verifierThreads = new Thread[resultString.size()]; + for (int i = 0; i < resultString.size(); i++) { + int j = i; + verifierThreads[i] = new Thread(() -> { + try { +// DID[j] = resultString.get(j); +// appname[j] = DID[j].concat("rec"); +// PeerID[j] = getValues(DATA_PATH + "DataTable.json", "peerid", "didHash", DID[j]); +// IPFSNetwork.swarmConnect(PeerID[j], ipfs); +// IPFSNetwork.forward(appname[j], SEND_PORT + j, PeerID[j]); + + senderSocket[j] = new Socket(resultString.get(j), RECEIVER_PORT); + cin[j] = new BufferedReader(new InputStreamReader(senderSocket[j].getInputStream())); + cout[j] = new PrintStream(senderSocket[j].getOutputStream()); + + //Sending operation + cout[j].println(operation); + + if(operation.equals("launch")){ + cout[j].println(filename); + } + + //send Sign(Token+JSONObject+TC), Token,TC,JSONObject + cout[j].println(dataVerify); + + + FileAccessFunctionsLogger.debug("Sent Data to other members" + dataVerify); + + String status = ""; + while ((status = cin[j].readLine()) == null) { + } + FileAccessFunctionsLogger.debug("Received Status & signatures from other verifiers" + status); + + if(status.contains("Error")) + error++; + else + valid++; + + while(error + valid < resultString.size()){ + } + //if(!error), then verify signatures + if (error == 0) { + String selfverifystatus = ""; + while ((selfverifystatus = cin[j].readLine()) == null) { + } + if (!selfverifystatus.contains("Error")) + selfverify++; + else + noverify++; + while (selfverify + noverify < resultString.size()){} + if (selfverify == resultString.size()) { + String signaturestatus = ""; + while ((signaturestatus = cin[j].readLine()) == null) { + } + + FileAccessFunctionsLogger.debug("Status: " + status); + JSONObject details = new JSONObject(signaturestatus); + String verifierSign = details.getString("signature"); + JSONObject verifierData = details.getJSONObject("data"); + + JSONObject reHashObject = new JSONObject(); + reHashObject.put("did", verifierData.getString("did")); + reHashObject.put("data", token + verifierData); + String hash = calculateHash(reHashObject.toString(), "SHA3-256"); + + JSONObject dataToVerify = new JSONObject(); + dataToVerify.put("did", verifierData.getString("did")); + dataToVerify.put("signature", verifierSign); + dataToVerify.put("hash", hash); + + FileAccessFunctionsLogger.debug("Verifying the signatures"); + if (verifySignature(dataToVerify.toString())) { + signatureSync(details); + + FileAccessFunctionsLogger.debug("Waiting for all Signatures"); + FileAccessFunctionsLogger.debug(SignatureDetails.length()); + FileAccessFunctionsLogger.debug(resultString.size()); + while (SignatureDetails.length() < resultString.size() + 1) { + + } + FileAccessFunctionsLogger.debug("Sending Signatures to all members including initiator"); + cout[j].println(SignatureDetails.toString()); + + String verificationStatus = ""; + while ((verificationStatus = cin[j].readLine()) == null) { + } + + FileAccessFunctionsLogger.debug("Verification Status of Signatures" + verificationStatus); + if (verificationStatus.equals("Verified")) + verifiedStatus++; + else + nonVerifiedStatus++; + + FileAccessFunctionsLogger.debug("verified Status: " + verifiedStatus); + FileAccessFunctionsLogger.debug("contract mem length: " + resultString.size()); + while (verifiedStatus + nonVerifiedStatus < resultString.size()) { + } + if (nonVerifiedStatus != 0) { + FileAccessFunctionsLogger.debug("Few contract members verification failed"); + launchStatus = false; + cin[j].close(); + cout[j].close(); + senderSocket[j].close(); + } + } else { + FileAccessFunctionsLogger.debug("Few contract members verification failed"); + nonVerifiedStatus++; + cout[j].println("error"); + launchStatus = false; + cin[j].close(); + cout[j].close(); + senderSocket[j].close(); + + } + // executeIPFSCommands("ipfs p2p close -t /p2p/" + PeerID[j]); + } else { + FileAccessFunctionsLogger.debug("Error: Init data not Verified"); + launchStatus = false; + nonVerifiedStatus++; + noverify++; + cin[j].close(); + cout[j].close(); + senderSocket[j].close(); + } + } else { + FileAccessFunctionsLogger.debug("Error: Data not Verified/invalid operation"); + launchStatus=false; + nonVerifiedStatus++; + cin[j].close(); + cout[j].close(); + senderSocket[j].close(); + } + //executeIPFSCommands(" ipfs p2p close -t /p2p/" + PeerID[j]); + //System.exit(1); + cin[j].close(); + cout[j].close(); + senderSocket[j].close(); + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + }); + verifierThreads[i].start(); + FileAccessFunctionsLogger.debug("Thread " + i + "Started"); + } + + while (verifiedStatus + nonVerifiedStatus < resultString.size()) { + } + + if(nonVerifiedStatus == 0) { + launchStatus = true; + FileAccessFunctionsLogger.debug("writing Initiator signature, did & fileHash to TokenChain"); + File tokenchainfile = new File(TOKENCHAIN_PATH + token + ".json"); + if (!tokenchainfile.exists()) { + tokenchainfile.createNewFile(); + writeToFile(TOKENCHAIN_PATH + token + ".json", new JSONArray().toString(), false); + } + + String tokenchainData = readFile(TOKENCHAIN_PATH + token + ".json"); + JSONArray tokenChainArray = new JSONArray(tokenchainData); + JSONObject tokenChainSignData = new JSONObject(); + tokenChainSignData.put("did", did); + tokenChainSignData.put("signature", sign); + tokenChainSignData.put("fileHash", hashObject.getString("fileHash")); + tokenChainArray.put(tokenChainSignData); + writeToFile(TOKENCHAIN_PATH + token + ".json", tokenChainArray.toString(), false); + + if(operation.equals("launch")) + { + FileAccessFunctionsLogger.debug("Writing fileHash, contractData and Token to Contracts.json"); + File contract = new File(DRIVE_PATH + "Contracts.json"); + if (!contract.exists()) { + contract.createNewFile(); + writeToFile(DRIVE_PATH + "Contracts.json", new JSONArray().toString(), false); + } + + String contractFile = readFile(DRIVE_PATH + "Contracts.json"); + JSONArray contractArray = new JSONArray(contractFile); + JSONObject innerObject = new JSONObject(); + innerObject.put("fileHash", hashObject.getString("fileHash")); + innerObject.put("fileName", filename); + innerObject.put("contractData", hashObject.getJSONArray("contractData")); + innerObject.put("token", token); + innerObject.put("status", true); + contractArray.put(innerObject); + writeToFile(DRIVE_PATH + "Contracts.json", contractArray.toString(), false); + } + } + else + return launchStatus; + return launchStatus; + } + + public static boolean tokenCheck(String token) throws JSONException { + Functions.pathSet(); + createRbxDrive(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + boolean status = false; + String contractFile = readFile(DRIVE_PATH + "Contracts.json"); + JSONArray contractDataFile = new JSONArray(contractFile); + for (int i = 0; i < contractDataFile.length(); i++) { + JSONObject innerObject = contractDataFile.getJSONObject(i); + if ((innerObject.getString("token")).equals(token) && innerObject.get("status").equals(true)) { + status = true; + break; + } + } + return status; + } + +} diff --git a/src/main/java/com/rubix/WAMPAC/FileAccess/Listen.java b/src/main/java/com/rubix/WAMPAC/FileAccess/Listen.java new file mode 100644 index 0000000000000000000000000000000000000000..7f3c0f3aad8fcc8ead935a5b21cb3142fed32bf6 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/FileAccess/Listen.java @@ -0,0 +1,356 @@ +package com.rubix.WAMPAC.FileAccess; + +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 java.io.*; +import java.net.ServerSocket; +import java.net.Socket; + +import static com.rubix.AuthenticateNode.Authenticate.verifySignature; +import static com.rubix.Resources.Functions.*; +import static com.rubix.WAMPAC.FileAccess.FileAccessFunctions.*; + +public class Listen implements Runnable { + public static Socket sklaunch; + public static ServerSocket sslaunch; + public static PrintStream output; + public static BufferedReader input; + public static String status; + public static Logger LaunchListenLogger = Logger.getLogger(Listen.class); + + @Override + public void run() { + while (true) { + Functions.pathSet(); + createRbxDrive(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + + IPFSNetwork.executeIPFSCommands("ipfs daemon"); + IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/" + IPFS_PORT); + + String didFile = readFile(DATA_PATH + "DID.json"); + JSONArray didArray = null; + try { + didArray = new JSONArray(didFile); + JSONObject didObject = didArray.getJSONObject(0); + String myDID = didObject.getString("didHash"); + +// JSONObject establishObject = new JSONObject(); +// establishObject.put("did", myDID); +// establishObject.put("appName", "rec"); +// listenThread(establishObject); +// String myPID = getValues(DATA_PATH + "DID.json", "peerid", "didHash", myDID); + //listen + LaunchListenLogger.debug("Listening for file access operations on " + RECEIVER_PORT); + sslaunch = new ServerSocket(RECEIVER_PORT); + sklaunch = sslaunch.accept(); + input = new BufferedReader(new InputStreamReader(sklaunch.getInputStream())); + output = new PrintStream(sklaunch.getOutputStream()); + + //fetch Token, TC, JSONObject, Sign(Token+JSONObject+TC) + LaunchListenLogger.debug("Waiting for operation from init"); + String op = ""; + while ((op = input.readLine()) == null) { + } + + String fileName = ""; + if(op.equals("launch")){ + while ((fileName = input.readLine()) == null) { + } + } + //fetch Token, TC, JSONObject, Sign(Token+JSONObject+TC) + LaunchListenLogger.debug("Waiting for data from Initiator"); + String dataCheck = ""; + while ((dataCheck = input.readLine()) == null) { + } + LaunchListenLogger.debug("Received data from initiator" + dataCheck); + JSONObject dataCheckObject = new JSONObject(dataCheck); + String signature = dataCheckObject.getString("signature"); + JSONObject hashObject = dataCheckObject.getJSONObject("data"); + String token = dataCheckObject.getString("token"); + String fileShared = hashObject.getString("fileHash"); + JSONArray launchContractData = hashObject.getJSONArray("contractData"); + String senderID="", oldHash=""; + File contract = new File(DRIVE_PATH + "Contracts.json"); + if (!contract.exists()) { + contract.createNewFile(); + writeToFile(DRIVE_PATH + "Contracts.json", new JSONArray().toString(), false); + } + + String contractFile = readFile(DRIVE_PATH + "Contracts.json"); + String fileHashFetched = ""; + JSONArray contractDataFetched = new JSONArray(); + JSONArray contractArray = new JSONArray(contractFile); + + if (op.equals("update")) { + oldHash = hashObject.getString("oldHash"); + senderID = hashObject.getString("did"); + String senderIP = hashObject.getString("ip"); + LaunchListenLogger.debug("oldhash: " + oldHash); + LaunchListenLogger.debug("newhash: " + fileShared); + if (tokenCheck(token)) { + LaunchListenLogger.debug("fetching contractData, prevFileIpfsHash using token from contracts.json"); + + for (int i = 0; i < contractArray.length(); i++) { + JSONObject innerObject = contractArray.getJSONObject(i); + if ((innerObject.get("token")).equals(token)) { + contractDataFetched = innerObject.getJSONArray("contractData"); + fileHashFetched = innerObject.getString("fileHash"); + } + } + //Check verifyWriteCount(InitDID, contract) from contractdata + LaunchListenLogger.debug("Checking write count for the did, version of the file, contract data"); + LaunchListenLogger.debug(verifyWriteCount(senderID, contractDataFetched, senderIP)); + LaunchListenLogger.debug(fileHashFetched.equals(oldHash)); + String launchDataHash = Functions.calculateHash(launchContractData.toString(),"SHA3-256"); + String contractDataFetchedHash = Functions.calculateHash(contractDataFetched.toString(), "SHA3-256"); + + if (verifyWriteCount(senderID, contractDataFetched, senderIP) && launchDataHash.equals(contractDataFetchedHash)&& fileHashFetched.equals(oldHash)) { + status = "true"; + output.println("valid"); + launchContractData = contractDataFetched; + } else { + status = "false"; + LaunchListenLogger.debug("No permission to update / Invalid Contract Data / Invalid FileHash"); + output.println("Error: Invalid Operation"); + sklaunch.close(); + sslaunch.close(); + LaunchListenLogger.debug( "No permission to update"); + } + } else { + status = "false"; + LaunchListenLogger.debug("Invalid token/ file not launched"); + output.println("Error: Invalid Operation"); + sklaunch.close(); + sslaunch.close(); + LaunchListenLogger.debug("Invalid Token"); + } + } else { + output.println("valid"); + status = "true"; + } + if(status.equals("true")) { + JSONObject reHashObject = new JSONObject(); + reHashObject.put("did", hashObject.getString("did")); + reHashObject.put("data", token + hashObject); + LaunchListenLogger.debug("Calculating hash for Initiator signature verification"); + String hash = Functions.calculateHash(reHashObject.toString(), "SHA3-256"); + + JSONObject dataToVerify = new JSONObject(); + dataToVerify.put("did", hashObject.getString("did")); + dataToVerify.put("signature", signature); + dataToVerify.put("hash", hash); + + //Verify the signature, if yes, replace InitDID with verifierDID and sign back + LaunchListenLogger.debug("Verifying Signatures"); + if (verifySignature(dataToVerify.toString())) { + output.println("selfverified"); + LaunchListenLogger.debug("Initiator Signature verified"); + hashObject.put("did", myDID); + + JSONObject signObject = new JSONObject(); + signObject.put("did", myDID); + signObject.put("data", token + hashObject); + String mySignature = sign(signObject.toString()); + + JSONObject details = new JSONObject(); + details.put("data", hashObject); + details.put("signature", mySignature); + //Send Sign or error + LaunchListenLogger.debug("Sending my signature"); + output.println(details.toString()); + + //fetch TC and contracts.json -> update the same + String SignatureData = ""; + while ((SignatureData = input.readLine()) == null) { + } + if (!SignatureData.contains("error")) { + LaunchListenLogger.debug("Received signatures list from initiator" + SignatureData); + JSONArray signaturesArray = new JSONArray(SignatureData); + int verifiedCount = 0, nonverifiedCount = 0; + LaunchListenLogger.debug("Signatures length" + signaturesArray.length()); + LaunchListenLogger.debug("contractMem length" + launchContractData.length()); + + if (signaturesArray.length() == launchContractData.length()) { + + LaunchListenLogger.debug("received all signatures and verifying"); + for (int k = 0; k < signaturesArray.length(); k++) { + JSONObject dataObj = signaturesArray.getJSONObject(k); + JSONObject dataObject = new JSONObject(); + dataObject.put("did", dataObj.getJSONObject("data").getString("did")); + dataObject.put("data", token + dataObj.getJSONObject("data")); + String hashMember = calculateHash(dataObject.toString(), "SHA3-256"); + + JSONObject dataToVerifyMember = new JSONObject(); + dataToVerifyMember.put("did", dataObj.getJSONObject("data").getString("did")); + dataToVerifyMember.put("signature", dataObj.getString("signature")); + dataToVerifyMember.put("hash", hashMember); + LaunchListenLogger.debug("Verifying signatures"); + if (verifySignature(dataToVerifyMember.toString())) + verifiedCount++; + else + nonverifiedCount++; + } + LaunchListenLogger.debug("verified count:" + verifiedCount); + if (nonverifiedCount == 0) { + if (verifiedCount == launchContractData.length()) { + pathSet(); + createRbxDrive(); + LaunchListenLogger.debug("All signatures verified"); + output.println("Verified"); + + //write into tokenchain + LaunchListenLogger.debug("Writing Initiator signature to tokenchain"); + File tokenchainfile = new File(TOKENCHAIN_PATH + token + ".json"); + if (!tokenchainfile.exists()) { + tokenchainfile.createNewFile(); + writeToFile(TOKENCHAIN_PATH + token + ".json", new JSONArray().toString(), false); + } + + String tokenchainData = readFile(tokenchainfile.getPath()); + JSONArray tokenChainArray = new JSONArray(tokenchainData); + dataToVerify.remove("hash"); + dataToVerify.put("fileHash", hashObject.getString("fileHash")); + tokenChainArray.put(dataToVerify); + writeToFile(TOKENCHAIN_PATH + token + ".json", tokenChainArray.toString(), false); + + if (op.equals("update")) { + pathSet(); + createRbxDrive(); + //update contract file + LaunchListenLogger.debug("Updating contract file"); + updateContract(senderID, fileShared, token); + + //adding new file to datapath + File oldfile = new File(DRIVE_PATH + oldHash); + if (oldfile.exists()) + oldfile.delete(); + + LaunchListenLogger.debug("Adding file shared to data path"); + File newFile = new File(DRIVE_PATH + fileShared); + if (!newFile.exists()) + newFile.createNewFile(); + String newData = IPFSNetwork.get(fileShared, ipfs); + writeToFile(DRIVE_PATH + fileShared, newData, false); + } + //write into fileTokenList + if (op.equals("launch")) { + pathSet(); + createRbxDrive(); + LaunchListenLogger.debug("Writing token to fileTokenList.json"); + File tokenfileList = new File(DRIVE_PATH + "fileTokenList.json"); + if (!tokenfileList.exists()) { + tokenfileList.createNewFile(); + writeToFile(DRIVE_PATH + "fileTokenList.json", new JSONArray().toString(), false); + } + String tokenData = readFile(DRIVE_PATH + "fileTokenList.json"); + JSONArray tokenArray = new JSONArray(tokenData); + JSONObject tokenObject = new JSONObject(); + tokenObject.put("tokenHash", token); + tokenArray.put(tokenObject); + writeToFile(DRIVE_PATH + "fileTokenList.json", tokenArray.toString(), false); + + LaunchListenLogger.debug("Updating token"); + + // write token in tokens path + + File tokenFile = new File(TOKENS_PATH + token); + LaunchListenLogger.debug("token path" + tokenFile); + if (!tokenFile.exists()) { + tokenFile.createNewFile(); + } + + String tokenContent = IPFSNetwork.get(token, ipfs); + LaunchListenLogger.debug("Updating token content: " + tokenContent); + writeToFile(TOKENS_PATH + token, tokenContent, false); + + LaunchListenLogger.debug("Updating contracts.json"); + + String contractFileData = readFile(DRIVE_PATH + "Contracts.json"); + JSONArray contractData = new JSONArray(contractFileData); + JSONObject innerObject = new JSONObject(); + innerObject.put("fileHash", hashObject.getString("fileHash")); + innerObject.put("contractData", hashObject.getJSONArray("contractData")); + innerObject.put("token", token); + innerObject.put("fileName", fileName); + innerObject.put("status", true); + contractData.put(innerObject); + + writeToFile(DRIVE_PATH + "Contracts.json", contractData.toString(), false); + + LaunchListenLogger.debug("Adding file shared to drive path"); + + File newFile = new File(DRIVE_PATH + fileShared); + if (!newFile.exists()) + newFile.createNewFile(); + + String data = IPFSNetwork.get(fileShared, ipfs); + writeToFile(DRIVE_PATH + fileShared, data, false); + + LaunchListenLogger.debug("Launch Successful" + token); + } + sklaunch.close(); + sslaunch.close(); + } else { + LaunchListenLogger.debug("All signatures not verified"); + output.println("Error: Invalid Signatures (Verification Failed)"); + sklaunch.close(); + sslaunch.close(); + // executeIPFSCommands("ipfs p2p close -l /p2p/" + myPID); + } + } else { + LaunchListenLogger.debug("All signatures not verified"); + output.println("Error: Invalid Signatures (Verification Failed)"); + sklaunch.close(); + sslaunch.close(); + // executeIPFSCommands("ipfs p2p close -l /p2p/" + myPID); + } + } else { + LaunchListenLogger.debug("All signatures(length) not collected"); + output.println("Error: Invalid Signatures (length)"); + sklaunch.close(); + sslaunch.close(); + // executeIPFSCommands("ipfs p2p close -l /p2p/" + myPID); + } + + } else { + LaunchListenLogger.debug("Initiator did not verify signatures"); + sklaunch.close(); + sslaunch.close(); + // executeIPFSCommands("ipfs p2p close -l /p2p/" + myPID); + } + }else { + LaunchListenLogger.debug("Initiator not authenticated"); + output.println("Error"); + sklaunch.close(); + sslaunch.close(); + // executeIPFSCommands("ipfs p2p close -l /p2p/" + myPID); + } + } + else { + LaunchListenLogger.debug("Update Checks failed"); + output.println("Error: Invalid Operation"); + sklaunch.close(); + sslaunch.close(); + } + } catch (JSONException | IOException | InterruptedException e) { + LaunchListenLogger.error("IO/JSON Exception Occurred", e); + try { + sklaunch.close(); + sslaunch.close(); + } catch (IOException ioException) { + LaunchListenLogger.error("IO Exception Occurred", e); + ioException.printStackTrace(); + } + e.printStackTrace(); + } + } + } +} diff --git a/src/main/java/com/rubix/WAMPAC/FileAccess/UIFunctions.java b/src/main/java/com/rubix/WAMPAC/FileAccess/UIFunctions.java new file mode 100644 index 0000000000000000000000000000000000000000..1bcf67461b0e849d15564c922506b68615e24da1 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/FileAccess/UIFunctions.java @@ -0,0 +1,135 @@ +package com.rubix.WAMPAC.FileAccess; + +import com.rubix.Resources.Functions; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; + +import static com.rubix.Resources.Functions.*; +import static com.rubix.WAMPAC.FileAccess.FileAccessFunctions.DRIVE_PATH; + +public class UIFunctions { + public static Logger UIFunctions = Logger.getLogger(UIFunctions.class); + public static int sharedFilesCount() { + Functions.pathSet(); + FileAccessFunctions.createRbxDrive(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + File file = new File(DRIVE_PATH + "fileTokenList.json"); + if (file.exists()) { + String fileList = readFile(file.toString()); + JSONArray fileArray = null; + try { + fileArray = new JSONArray(fileList); + } catch (JSONException e) { + UIFunctions.error("JSON Exception Occurred", e); + e.printStackTrace(); + } + UIFunctions.debug("Shared Files Length: " + fileArray.length()); + return fileArray.length(); + } + else + return 0; + } + + public static ArrayList<String> sharedFilesList(){ + Functions.pathSet(); + FileAccessFunctions.createRbxDrive(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + ArrayList<String> filesList = new ArrayList<String>(); + File file = new File(DRIVE_PATH + "Contracts.json"); + if (file.exists()) { + String contractList = readFile(file.toString()); + JSONArray fileArray = null; + try { + fileArray = new JSONArray(contractList); + for(int i = 0; i < fileArray.length(); i++){ + JSONObject fileObject = fileArray.getJSONObject(i); + filesList.add(i, fileObject.getString("fileName")); + } + } catch (JSONException e) { + UIFunctions.error("JSON Exception Occurred", e); + e.printStackTrace(); + } + UIFunctions.debug("List of files: " + filesList); + } + else + UIFunctions.debug("File does not exist"); + return filesList; + } + + public static JSONObject sharedFileDetails(String fileName) throws JSONException { + Functions.pathSet(); + FileAccessFunctions.createRbxDrive(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + JSONObject details = new JSONObject(); + File file = new File(DRIVE_PATH + "Contracts.json"); + if (file.exists()) { + String contractList = readFile(file.toString()); + try { + JSONArray fileArray = new JSONArray(contractList); + for(int i = 0; i < fileArray.length(); i++){ + JSONObject fileObject = fileArray.getJSONObject(i); + if(fileObject.getString("fileName").equals(fileName)) { + details = fileObject; + String token = details.getString("token"); + File tokenChainFile = new File(TOKENCHAIN_PATH + token + ".json"); + if(tokenChainFile.exists()) { + String tokenChainData = readFile(tokenChainFile.toString()); + JSONArray tokenChainArray = new JSONArray(tokenChainData); + details.put("accessCount", tokenChainArray.length()); + break; + }else { + details.put("accessCount", 0); + break; + } + } + } + } catch (JSONException e) { + UIFunctions.error("JSON Exception Occurred", e); + e.printStackTrace(); + } + } + else { + UIFunctions.debug("File does not exist"); + details.put("Error", "File does not exist"); + } + return details; + } + + public static JSONObject sharedFileMetaData(String fileName) throws JSONException { + Functions.pathSet(); + FileAccessFunctions.createRbxDrive(); + PropertyConfigurator.configure(LOGGER_PATH + "log4jWallet.properties"); + JSONObject details = new JSONObject(); + File file = new File(DRIVE_PATH + "Contracts.json"); + if (file.exists()) { + String contractList = readFile(file.toString()); + try { + JSONArray fileArray = new JSONArray(contractList); + for(int i = 0; i < fileArray.length(); i++){ + JSONObject fileObject = fileArray.getJSONObject(i); + if(fileObject.getString("fileName").equals(fileName)) { + details.put("token", fileObject.getString("token")); + details.put("fileHash", fileObject.getString("fileHash")); + break; + } + } + } catch (JSONException e) { + UIFunctions.error("JSON Exception Occurred", e); + e.printStackTrace(); + } + } + else { + UIFunctions.debug("File does not exist"); + details.put("Error", "File does not exist"); + } + return details; + } + + +} diff --git a/src/main/java/com/rubix/WAMPAC/WampacApplication.java b/src/main/java/com/rubix/WAMPAC/WampacApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..0188d08b8697ee6219f3069a1be1e7b8a4c76025 --- /dev/null +++ b/src/main/java/com/rubix/WAMPAC/WampacApplication.java @@ -0,0 +1,39 @@ +package com.rubix.WAMPAC; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@SpringBootApplication +public class WampacApplication { + + public static void main(String[] args) { + System.setProperty("server.port", "1898"); + SpringApplication.run(WampacApplication.class, args); + } + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + + registry.addMapping("/**").allowedOrigins("http://localhost:9000"); + } + }; + } + + @Configuration + @EnableWebMvc + public class WebConfig implements WebMvcConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**"); + } + } +}