public Grader(string BasePath) { FileSystemWatcher watcher = new FileSystemWatcher(); //String CommandFolder = BasePath + File.separator + Config.TAG_COMMAND; this.BasePath = BasePath; watcher.Path = BasePath + Path.DirectorySeparatorChar + Config.TAG_DETECTED; Console.WriteLine(watcher.Path + " Watching"); RAIDA.ActiveRAIDA = RAIDA.GetInstance(); FS = new FileSystem(FolderManager.FolderManager.RootPath + Path.DirectorySeparatorChar + Config.TAG_DETECTED); RAIDA.FileSystem = FS; RAIDA.ActiveRAIDA.FS = FS; /* Watch for changes in LastAccess and LastWrite times, and * the renaming of files or directories. */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. watcher.Filter = "*.stack"; // Add event handlers. // watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); // watcher.Deleted += new FileSystemEventHandler(OnChanged); //watcher.Renamed += new RenamedEventHandler(OnRenamed); watcher.EnableRaisingEvents = true; }
private static String GetLogFileName(int num) { Node node = RAIDA.GetInstance().nodes[num]; return((num) + "_" + node.RAIDANodeStatus + "_" + node.echoresponses.milliseconds + "_" + node.internalExecutionTime + ".txt"); }
public static RAIDA GetInstance(Network network) { RAIDA raida = new RAIDA(network); raida.FS = FileSystem; return(raida); }
public async static Task ProcessCoins(bool ChangeANs = true) { var networks = (from x in IFileSystem.importCoins select x.nn).Distinct().ToList(); TimeSpan ts = new TimeSpan(); DateTime before = DateTime.Now; DateTime after; foreach (var nn in networks) { ActiveRAIDA = (from x in RAIDA.networks where x.NetworkNumber == nn select x).FirstOrDefault(); int NetworkExists = (from x in RAIDA.networks where x.NetworkNumber == nn select x).Count(); if (NetworkExists > 0) { updateLog("Starting Coins detection for Network " + nn); await ProcessNetworkCoins(nn, ChangeANs); updateLog("Coins detection for Network " + nn + "Finished."); } } after = DateTime.Now; ts = after.Subtract(before); Debug.WriteLine("Detection Completed in : " + ts.TotalMilliseconds / 1000); updateLog("Detection Completed in : " + ts.TotalMilliseconds / 1000); }
private async static Task ProcessInput(int input) { switch (input) { case 1: await EchoRaida(); break; case 2: showCoins(); break; case 3: //await detect(); await RAIDA.ProcessNetworkCoins(NetworkNumber); break; case 4: export(); break; case 6: try { Process.Start(FS.RootPath); } catch (Exception e) { updateLog(e.Message); } ShowFolders(); break; case 5: Fix(); //fix(timeout); break; case 7: help(); break; case 8: Console.Write("Enter New Network Number - "); int nn = Convert.ToInt16(Console.ReadLine()); await SwitchNetwork(nn); break; case 9: await SendCoinsTT(); break; default: break; } }
}//end fix private void resumeImport() { int count = Directory.GetFiles(FS.SuspectFolder).Length; if (count > 0) { new Thread(() => { Thread.CurrentThread.IsBackground = true; //EchoRaidas().Wait(); raida = RAIDA.GetInstance(); if (raida.NotReadyCount > 8) { // insufficientRAIDA(); return; } else { import(); } /* run your code here */ }).Start(); } }
// Return Main RAIDA Network populated with default Nodes Addresses(Network 1) public static RAIDA GetInstance() { if (MainNetwork != null) { return(MainNetwork); } else { MainNetwork = new RAIDA(); return(MainNetwork); } }
// This method was introduced breaking the previously used Singleton pattern. // This was done in order to support multiple networks concurrently. // We can now have multiple RAIDA objects each containing different networks // RAIDA details are read from Directory URL first. // In case of failure, it falls back to a file on the file system public static List <RAIDA> Instantiate() { string nodesJson = ""; networks.Clear(); using (WebClient client = new WebClient()) { try { nodesJson = client.DownloadString(Config.URL_DIRECTORY); } catch (Exception e) { Console.WriteLine(e.Message); if (System.IO.File.Exists("directory.json")) { nodesJson = System.IO.File.ReadAllText(Environment.CurrentDirectory + @"\directory.json"); } else { Exception raidaException = new Exception("RAIDA instantiation failed. No Directory found on server or local path"); throw raidaException; } } } try { RAIDADirectory dir = JsonConvert.DeserializeObject <RAIDADirectory>(nodesJson); foreach (var network in dir.networks) { networks.Add(RAIDA.GetInstance(network)); } } catch (Exception e) { Exception raidaException = new Exception("RAIDA instantiation failed. No Directory found on server or local path"); throw raidaException; } if (networks == null) { Exception raidaException = new Exception("RAIDA instantiation failed. No Directory found on server or local path"); throw raidaException; } if (networks.Count == 0) { Exception raidaException = new Exception("RAIDA instantiation failed. No Directory found on server or local path"); throw raidaException; } return(networks); }
public static async Task EchoRaidas(bool scanAll = false, bool silent = false) { // IsEchoRunning = true; var networks = (from x in RAIDA.networks select x).Distinct().ToList(); var echos = RAIDA.GetInstance().GetEchoTasks(); RAIDA raida = RAIDA.GetInstance(); await Task.WhenAll(echos.AsParallel().Select(async task => await task())); Console.WriteLine("Ready Count - " + raida.ReadyCount); Console.WriteLine("Not Ready Count - " + raida.NotReadyCount); }
static async void DownloadCoin(string hash) { using (System.Net.Http.HttpClient cli = new System.Net.Http.HttpClient()) { var httpResponse = await cli.GetAsync("https://escrow.cloudcoin.digital/cc.php?h=" + hash); var ccstack = await httpResponse.Content.ReadAsStringAsync(); File.WriteAllText(FS.ImportFolder + Path.DirectorySeparatorChar + "CloudCoins.FromTrustedTrade.stack", ccstack); await RAIDA.ProcessCoins(NetworkNumber); DisplayMenu(); } }
} //end detect public async Task <Response> Detect() { CloudCoin coin = RAIDA.GetInstance().coin; Response detectResponse = new Response(); detectResponse.fullRequest = this.FullUrl + "detect?nn=" + coin.nn + "&sn=" + coin.sn + "&an=" + coin.an[NodeNumber - 1] + "&pan=" + coin.pan[NodeNumber - 1] + "&denomination=" + coin.denomination + "&b=t"; DateTime before = DateTime.Now; coin.SetAnsToPans(); try { detectResponse.fullResponse = await Utils.GetHtmlFromURL(detectResponse.fullRequest); DateTime after = DateTime.Now; TimeSpan ts = after.Subtract(before); detectResponse.milliseconds = Convert.ToInt32(ts.Milliseconds); coin.response[this.NodeNumber - 1] = detectResponse; if (detectResponse.fullResponse.Contains("pass")) { detectResponse.outcome = "pass"; detectResponse.success = true; FailsDetect = false; } else if (detectResponse.fullResponse.Contains("fail") && detectResponse.fullResponse.Length < 200) //less than 200 incase their is a fail message inside errored page { detectResponse.outcome = "fail"; detectResponse.success = false; RAIDANodeStatus = NodeStatus.Ready; FailsDetect = true; //RAIDA_Status.failsDetect[RAIDANumber] = true; } else { detectResponse.outcome = "error"; detectResponse.success = false; RAIDANodeStatus = NodeStatus.NotReady; FailsDetect = true; //RAIDA_Status.failsDetect[RAIDANumber] = true; } } catch (Exception ex) { detectResponse.outcome = "error"; detectResponse.fullResponse = ex.InnerException.Message; detectResponse.success = false; } return(detectResponse); } //end detect
public List <Task> GetDetectTasks() { var raida = RAIDA.GetInstance(); CloudCoin cc = this; int i = 0; for (int j = 0; j < Config.NodeCount; j++) { Task t = Task.Factory.StartNew(() => raida.nodes[i].Detect(cc)); detectTaskList.Add(t); } return(detectTaskList); }
} // end show folders public static void Setup() { // Create the Folder Structure FS.CreateFolderStructure(); // Populate RAIDA Nodes raida = RAIDA.GetInstance(); //raida.Echo(); FS.LoadFileSystem(); //Connect to Trusted Trade Socket tts = new TrustedTradeSocket("wss://escrow.cloudcoin.digital/ws/", 10, OnWord, OnStatusChange, OnReceive, OnProgress); tts.Connect().Wait(); //Load Local Coins // Console.Read(); }
}// end of constructor private Node[] getTrustedServers(int raidaNumber) { Node[] result = new Node[8]; var i = raidaNumber; return(result = new Node[] { RAIDA.GetInstance().nodes[(i + 19) % 25], RAIDA.GetInstance().nodes[(i + 20) % 25], RAIDA.GetInstance().nodes[(i + 21) % 25], RAIDA.GetInstance().nodes[(i + 24) % 25], RAIDA.GetInstance().nodes[(i + 26) % 25], RAIDA.GetInstance().nodes[(i + 29) % 25], RAIDA.GetInstance().nodes[(i + 30) % 25], RAIDA.GetInstance().nodes[(i + 31) % 25] }); }
public void Setup() { FS = new FileSystem(RootPath); // Create the Folder Structure FS.CreateFolderStructure(); FS.CopyTemplates(); // Populate RAIDA Nodes raida = RAIDA.GetInstance(); raida.FS = FS; //CoinDetected += Raida_CoinDetected; //raida.Echo(); FS.ClearCoins(FS.PreDetectFolder); FS.ClearCoins(FS.DetectedFolder); FS.LoadFileSystem(); }
public async Task <string> GetTicketResponse(int nn, int sn, String an, int d) { RAIDA raida = RAIDA.GetInstance(); Response get_ticketResponse = new Response(); get_ticketResponse.fullRequest = FullUrl + "get_ticket?nn=" + nn + "&sn=" + sn + "&an=" + an + "&pan=" + an + "&denomination=" + d; DateTime before = DateTime.Now; try { get_ticketResponse.fullResponse = await Utils.GetHtmlFromURL(get_ticketResponse.fullRequest); Console.WriteLine(get_ticketResponse.fullResponse); DateTime after = DateTime.Now; TimeSpan ts = after.Subtract(before); get_ticketResponse.milliseconds = Convert.ToInt32(ts.Milliseconds); if (get_ticketResponse.fullResponse.Contains("ticket")) { String[] KeyPairs = get_ticketResponse.fullResponse.Split(','); String message = KeyPairs[3]; int startTicket = Utils.ordinalIndexOf(message, "\"", 3) + 2; int endTicket = Utils.ordinalIndexOf(message, "\"", 4) - startTicket; get_ticketResponse.outcome = message.Substring(startTicket - 1, endTicket + 1); //This is the ticket or message get_ticketResponse.success = true; HasTicket = true; ticketHistory = TicketHistory.Success; Ticket = get_ticketResponse.outcome; } else { get_ticketResponse.success = false; HasTicket = false; ticketHistory = TicketHistory.Failed; } //end if } catch (Exception ex) { get_ticketResponse.outcome = "error"; get_ticketResponse.fullResponse = ex.InnerException.Message; get_ticketResponse.success = false; HasTicket = false; ticketHistory = TicketHistory.Failed; } //end try catch //return get_ticketResponse; return(get_ticketResponse.fullResponse); } //end get ticket
public async Task EchoRaidas(bool scanAll = false, bool silent = false) { IsEchoRunning = true; var networks = (from x in RAIDA.networks select x).Distinct().ToList(); if (silent) { updateLog("----------------------------------"); updateLog(String.Format("Starting Echo to RAIDA")); updateLog("----------------------------------"); UpdateCELog("----------------------------------"); UpdateCELog(String.Format("Starting Echo to RAIDA")); UpdateCELog("----------------------------------"); } var echos = RAIDA.GetInstance().GetEchoTasks(); raida = RAIDA.GetInstance(); await Task.WhenAll(echos.AsParallel().Select(async task => await task())); if (silent) { updateLog("Ready Count: " + raida.ReadyCount); updateLog("Not Ready Count: " + raida.NotReadyCount); updateLog("-----------------------------------"); UpdateCELog("Ready Count: " + raida.ReadyCount); UpdateCELog("Not Ready Count: " + raida.NotReadyCount); UpdateCELog("-----------------------------------"); } App.Current.Dispatcher.Invoke(delegate { updateLEDs(); }); IsEchoRunning = false; }
public async static Task SwitchNetwork(int NewNetworkNumber) { int oldRAIDANumber = NetworkNumber; RAIDA oldRAIDA = raida; NetworkNumber = NewNetworkNumber; raida = (from x in RAIDA.networks where x.NetworkNumber == NetworkNumber select x).FirstOrDefault(); if (raida == null) { updateLog("Selected Network Number not found. Reverting to previous network."); raida = oldRAIDA; } else { updateLog("Network Number set to " + NetworkNumber); await EchoRaida(); } }
} // end setAnsToPans public void SetAnsToPansIfPassed(bool partial = false) { // now set all ans that passed to the new pans char[] pownArray = pown.ToCharArray(); for (int i = 0; (i < Config.NodeCount); i++) { if (pownArray[i] == 'p') //1 means pass { an[i] = pan[i]; } else if (pownArray[i] == 'u' && !(RAIDA.GetInstance().nodes[i].RAIDANodeStatus == NodeStatus.NotReady) && partial == false) //Timed out but there server echoed. So it probably changed the PAN just too slow of a response { an[i] = pan[i]; } else { // Just keep the ans and do not change. Hopefully they are not fracked. } } // for each guid in coin } // end set ans to pans if passed
private static void OnChanged(object source, FileSystemEventArgs e) { // Specify what is done when a file is changed, created, or deleted. Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Renamed) { Console.WriteLine("\n" + Path.GetFileName(e.FullPath)); if (Path.GetFileName(e.FullPath).Contains("echoer")) { //Console.WriteLine("caught"); EchoRaidas().Wait(); for (int i = 0; i < RAIDA.GetInstance().nodes.Length; i++) { string fileName = EchoerLogsFolder + Path.DirectorySeparatorChar + GetLogFileName(i); File.WriteAllText(fileName, "{\n" + " \"url\":\"" + RAIDA.GetInstance().nodes[i].FullUrl + "\"\n" + "}"); } } } }
public void fix() { RAIDA raida = RAIDA.GetInstance(); EchoRaidas(false, false).Wait(); if (raida.NotReadyCount > 8) { insufficientRAIDA(); return; } UpdateCELog(" Fracked coins present in Fracked folder!Frack Fixing in progress! DO NOT TURN OFF CloudCoinCE application!!!!"); UpdateCELog(" Fixing fracked coins can take many minutes."); UpdateCELog(" If your coins are not completely fixed, fix fracked again."); UpdateCELog(" Attempting to fix all fracked coins."); //Frack_Fixer fixer = new Frack_Fixer(FS, timeout); fixer.FixAll(); }//end fix
public static void SetupRAIDA() { RAIDA.FileSystem = new FileSystem(rootFolder); try { RAIDA.Instantiate(); } catch (Exception e) { Console.WriteLine(e.Message); Environment.Exit(1); } if (RAIDA.networks.Count == 0) { updateLog("No Valid Network found.Quitting!!"); Environment.Exit(1); } else { updateLog(RAIDA.networks.Count + " Networks found."); raida = (from x in RAIDA.networks where x.NetworkNumber == NetworkNumber select x).FirstOrDefault(); raida.FS = FS; RAIDA.ActiveRAIDA = raida; if (raida == null) { updateLog("Selected Network Number not found. Quitting."); Environment.Exit(0); } else { updateLog("Network Number set to " + NetworkNumber); } } //networks[0] }
private void cmdPown_Click(object sender, RoutedEventArgs e) { UpdateCELog(" User Input : Deposit"); printStarLine(); updateLog("Starting CloudCoin Import."); updateLog(" Please do not close the CloudCoin CE program until it is finished."); updateLog(" Otherwise it may result in loss of CloudCoins."); printStarLine(); int count = FS.LoadFolderCoins(FS.ImportFolder).Count(); if (count == 0) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Cloudcoins (*.stack, *.jpg,*.jpeg)|*.stack;*.jpg;*.jpeg|Stack files (*.stack)|*.stack|Jpeg files (*.jpg)|*.jpg|All files (*.*)|*.*"; openFileDialog.InitialDirectory = FS.ImportFolder.Substring(0, FS.ImportFolder.Length - 1).Replace("\\\\", "\\"); openFileDialog.Multiselect = true; if (openFileDialog.ShowDialog() == true) { foreach (string filename in openFileDialog.FileNames) { try { if (!File.Exists(FS.ImportFolder + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileName(filename))) { File.Move(filename, FS.ImportFolder + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileName(filename)); } else { string msg = "File " + filename + " already exists. Do you want to overwrite it?"; MessageBoxResult result = MessageBox.Show( msg, "CloudCoins", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.Yes) { try { File.Delete(FS.ImportFolder + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileName(filename)); File.Move(filename, FS.ImportFolder + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileName(filename)); } catch (Exception ex) { } } } } catch (Exception ex) { updateLog(ex.Message); } } } else { return; } } if (raida.NotReadyCount > 8) { insufficientRAIDA(); return; } new Thread(async() => { Thread.CurrentThread.IsBackground = true; fixer.continueExecution = false; UpdateCELog("Starting Detect.."); printStarLine(); await RAIDA.ProcessCoins(true); ShowCoins(); }).Start(); }
public Translator(string BasePath) { FileSystemWatcher watcher = new FileSystemWatcher(); FileSystemWatcher echoerwatcher = new FileSystemWatcher(); FileSystemWatcher authenticatorwatcher = new FileSystemWatcher(); FileSystemWatcher lossfixerwatcher = new FileSystemWatcher(); FileSystemWatcher showcoinswatcher = new FileSystemWatcher(); //String CommandFolder = BasePath + File.separator + Config.TAG_COMMAND; this.BasePath = BasePath; LogsFolder = BasePath + Path.DirectorySeparatorChar + Config.TAG_LOGS; EchoerLogsFolder = BasePath + Path.DirectorySeparatorChar + Config.TAG_LOGS + Path.DirectorySeparatorChar + "Echoer"; AuthenticatorLogsFolder = BasePath + Path.DirectorySeparatorChar + Config.TAG_LOGS + Path.DirectorySeparatorChar + "authenticator"; LossFixerLogsFolder = BasePath + Path.DirectorySeparatorChar + Config.TAG_LOGS + Path.DirectorySeparatorChar + "LossFixer"; ShowCoinsLogsFolder = BasePath + Path.DirectorySeparatorChar + Config.TAG_LOGS + Path.DirectorySeparatorChar + "ShowCoins"; watcher.Path = BasePath + Path.DirectorySeparatorChar + Config.TAG_LOGS; echoerwatcher.Path = EchoerLogsFolder; authenticatorwatcher.Path = AuthenticatorLogsFolder; lossfixerwatcher.Path = LossFixerLogsFolder; showcoinswatcher.Path = ShowCoinsLogsFolder; Console.WriteLine(watcher.Path + " Watching"); RAIDA.ActiveRAIDA = RAIDA.GetInstance(); FS = new FileSystem(FolderManager.FolderManager.RootPath + Path.DirectorySeparatorChar + Config.TAG_LOGS); RAIDA.FileSystem = FS; RAIDA.ActiveRAIDA.FS = FS; /* Watch for changes in LastAccess and LastWrite times, and * the renaming of files or directories. */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. watcher.Filter = "*.stack"; echoerwatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. //echoerwatcher.Filter = "*.txt"; authenticatorwatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. authenticatorwatcher.Filter = "*.txt"; lossfixerwatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. lossfixerwatcher.Filter = "*.txt"; showcoinswatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. showcoinswatcher.Filter = "*.txt"; // Add event handlers. // watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); // watcher.Deleted += new FileSystemEventHandler(OnChanged); //watcher.Renamed += new RenamedEventHandler(OnRenamed); watcher.EnableRaisingEvents = true; echoerwatcher.Created += new FileSystemEventHandler(EchoerOnChanged); authenticatorwatcher.Created += new FileSystemEventHandler(EchoerOnChanged); showcoinswatcher.Created += new FileSystemEventHandler(EchoerOnChanged); lossfixerwatcher.Created += new FileSystemEventHandler(EchoerOnChanged); echoerwatcher.EnableRaisingEvents = true; watcher.EnableRaisingEvents = true; watcher.EnableRaisingEvents = true; watcher.EnableRaisingEvents = true; Console.WriteLine("Echoer Watcher field - " + echoerwatcher.Path); }
public static bool echoRaida() { RAIDA_Status.resetEcho(); RAIDA raida1 = new RAIDA(); Response[] results = raida1.echoAll(15000); int totalReady = 0; Console.Out.WriteLine(""); //For every RAIDA check its results int longestCountryName = 15; Console.Out.WriteLine(); for (int i = 0; i < 25; i++) { int padding = longestCountryName - RAIDA.countries[i].Length; string strPad = ""; for (int j = 0; j < padding; j++) { strPad += " "; }//end for padding // Console.Out.Write(RAIDA_Status.failsEcho[i]); if (RAIDA_Status.failsEcho[i]) { Console.ForegroundColor = ConsoleColor.Red; Console.Out.Write(strPad + RAIDA.countries[i]); } else { Console.ForegroundColor = ConsoleColor.Green; Console.Out.Write(strPad + RAIDA.countries[i]); totalReady++; } if (i == 4 || i == 9 || i == 14 || i == 19) { Console.WriteLine(); } }//end for Console.ForegroundColor = ConsoleColor.White; Console.Out.WriteLine(""); Console.Out.WriteLine(""); Console.Out.Write(" RAIDA Health: " + totalReady + " / 25: ");//"RAIDA Health: " + totalReady ); //Check if enough are good if (totalReady < 16)// { Console.ForegroundColor = ConsoleColor.Red; Console.Out.WriteLine(" Not enough RAIDA servers can be contacted to import new coins."); // ); Console.Out.WriteLine(" Is your device connected to the Internet?"); // ); Console.Out.WriteLine(" Is a router blocking your connection?"); // ); Console.ForegroundColor = ConsoleColor.White; return(false); } else { Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine("The RAIDA is ready for counterfeit detection.");// ); Console.ForegroundColor = ConsoleColor.White; return(true); } //end if enough RAIDA } //End echo
public static void Main(params string[] args) { Setup(); initConfig(); updateLog("Loading Network Directory"); SetupRAIDA(); FS.LoadFileSystem(); RAIDA.logger = logger; fixer = new Frack_Fixer(FS, Config.milliSecondsToTimeOut); Console.Clear(); // Program.exe <-g|--greeting|-$ <greeting>> [name <fullname>] // [-?|-h|--help] [-u|--uppercase] #region CommandLineArguments CommandLineApplication commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: false); CommandArgument names = null; commandLineApplication.Command("name", (target) => names = target.Argument( "fullname", "Enter the full name of the person to be greeted.", multipleValues: true)); CommandOption greeting = commandLineApplication.Option( "-$|-g |--greeting <greeting>", "The greeting to display. The greeting supports" + " a format string where {fullname} will be " + "substituted with the full name.", CommandOptionType.NoValue); CommandOption uppercase = commandLineApplication.Option( "-u | --uppercase", "Display the greeting in uppercase.", CommandOptionType.NoValue); commandLineApplication.HelpOption("-? | -h | --help"); CommandOption echo = commandLineApplication.Option( "-$|-e |--echo ", "The greeting to display. The greeting supports" + " a format string where {fullname} will be " + "substituted with the full name.", CommandOptionType.NoValue); CommandOption total = commandLineApplication.Option( "-$|-b |--bank ", "Shows details of your coins in bank.", CommandOptionType.NoValue); CommandOption backup = commandLineApplication.Option( "-$|-ba |--backup ", "Backup your coins to specified folder.", CommandOptionType.SingleValue); CommandOption folders = commandLineApplication.Option( "-$|-f |--folders ", "The command to display CloudCoin Working Folder Structure", CommandOptionType.NoValue); CommandOption pown = commandLineApplication.Option( "-$|-p |--pown ", "The command to pown/detect/import your CloudCoins.", CommandOptionType.NoValue); CommandOption detection = commandLineApplication.Option( "-$|-d |--detect ", "The command to pown/detect/import your CloudCoins.", CommandOptionType.NoValue); CommandOption import = commandLineApplication.Option( "-$|-i |--import ", "The command to pown/detect/import your CloudCoins.", CommandOptionType.NoValue); #endregion if (args.Length < 1) { printWelcome(); while (true) { try { int input = DisplayMenu(); ProcessInput(input).Wait(); if (input == 10) { break; } } catch (Exception e) { break; } } } else { commandLineApplication.OnExecute(async() => { if (echo.HasValue()) { //ech(); await EchoRaida(); } if (folders.HasValue()) { ShowFolders(); } if (pown.HasValue() || detection.HasValue() || import.HasValue()) { await RAIDA.ProcessNetworkCoins(NetworkNumber); } if (greeting.HasValue()) { printWelcome(); } if (total.HasValue()) { showCoins(); } if (backup.HasValue()) { Console.WriteLine(backup.Value()); } return(0); }); commandLineApplication.Execute(args); } }
} //end is gradable pass public String[] grade() { int total = Config.NodeCount; int passed = response.Where(x => x.outcome == "pass").Count(); int failed = response.Where(x => x.outcome == "fail").Count(); int other = total - passed - failed; if (passed > Config.PassCount) { DetectResult = DetectionStatus.Passed; } else { DetectResult = DetectionStatus.Failed; } String passedDesc = ""; String failedDesc = ""; String otherDesc = ""; // for each status // Calculate passed if (passed == 25) { passedDesc = "100% Passed!"; } else if (passed > 17) { passedDesc = "Super Majority"; } else if (passed > 13) { passedDesc = "Majority"; } else if (passed == 0) { passedDesc = "None"; } else if (passed < 5) { passedDesc = "Super Minority"; } else { passedDesc = "Minority"; } // Calculate failed if (failed == 25) { failedDesc = "100% Failed!"; } else if (failed > 17) { failedDesc = "Super Majority"; } else if (failed > 13) { failedDesc = "Majority"; } else if (failed == 0) { failedDesc = "None"; } else if (failed < 5) { failedDesc = "Super Minority"; } else { failedDesc = "Minority"; } // Calcualte Other RAIDA Servers did not help. switch (other) { case 0: otherDesc = "100% of RAIDA responded"; break; case 1: case 2: otherDesc = "Two or less RAIDA errors"; break; case 3: case 4: otherDesc = "Four or less RAIDA errors"; break; case 5: case 6: otherDesc = "Six or less RAIDA errors"; break; case 7: case 8: case 9: case 10: case 11: case 12: otherDesc = "Between 7 and 12 RAIDA errors"; break; case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: otherDesc = "RAIDA total failure"; break; default: otherDesc = "FAILED TO EVALUATE RAIDA HEALTH"; break; } // end RAIDA other errors and unknowns // Coin will go to bank, counterfeit or fracked if (other > 12) { // not enough RAIDA to have a quorum folder = RAIDA.GetInstance().FS.SuspectFolder; } else if (failed > passed) { // failed out numbers passed with a quorum: Counterfeit folder = RAIDA.GetInstance().FS.CounterfeitFolder; } else if (failed > 0) { // The quorum majority said the coin passed but some disagreed: fracked. folder = RAIDA.GetInstance().FS.FrackedFolder; } else { // No fails, all passes: bank folder = RAIDA.GetInstance().FS.BankFolder; } gradeStatus[0] = passedDesc; gradeStatus[1] = failedDesc; gradeStatus[2] = otherDesc; return(this.gradeStatus); } // end gradeStatus
private static async void OnChangedAsync(object source, FileSystemEventArgs e) { // Specify what is done when a file is changed, created, or deleted. Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Renamed) { Console.WriteLine("\n" + Path.GetFileName(e.FullPath)); //if (Path.GetFileName(e.FullPath).Contains("erase")) { Console.WriteLine("caught erase command"); string jsonText = ""; try { FileStream reader = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read); using (var sr = new StreamReader(reader, Encoding.Default)) { jsonText = sr.ReadToEnd(); // read the stream //... } var jo = Newtonsoft.Json.Linq.JObject.Parse(@jsonText); string account = jo.GetValue("account").ToString(); string command = jo.GetValue("command").ToString(); string sourceLocation = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "accounts" + Path.DirectorySeparatorChar + account; string commandPath = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "Commands"; string recieptsPath = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "Receipts"; string logsPath = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "Logs"; string userLogsLocation = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "accounts" + Path.DirectorySeparatorChar + account + Path.DirectorySeparatorChar + Config.TAG_LOGS; string userRecieptsLocation = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "accounts" + Path.DirectorySeparatorChar + account + Path.DirectorySeparatorChar + "Receipts"; string suspectLocation = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "accounts" + Path.DirectorySeparatorChar + account + Path.DirectorySeparatorChar + "Suspect"; string detectedLocation = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "accounts" + Path.DirectorySeparatorChar + account + Path.DirectorySeparatorChar + "Detected"; string predetectLocation = FolderManager.FolderManager.BasePath + Path.DirectorySeparatorChar + "accounts" + Path.DirectorySeparatorChar + account + Path.DirectorySeparatorChar + "Predetect"; if (command == "pown") { var suspectcoins = FS.LoadFolderCoins(suspectLocation); Array.ForEach(Directory.GetFiles(predetectLocation), delegate(string path) { File.Delete(path); }); foreach (var coin in suspectcoins) { FS.WriteCoin(coin, predetectLocation); } var predetectCoins = FS.LoadFolderCoins(predetectLocation); int LotCount = predetectCoins.Count() / Config.MultiDetectLoad; if (predetectCoins.Count() % Config.MultiDetectLoad > 0) { LotCount++; } ProgressChangedEventArgs pge = new ProgressChangedEventArgs(); int CoinCount = 0; int totalCoinCount = predetectCoins.Count(); RAIDA raida = RAIDA.GetInstance(); RAIDA.ActiveRAIDA = raida; for (int i = 0; i < LotCount; i++) { //Pick up 200 Coins and send them to RAIDA var coins = predetectCoins.Skip(i * Config.MultiDetectLoad).Take(Config.MultiDetectLoad); try { raida.coins = coins; var tasks = raida.GetMultiDetectTasks(coins.ToArray(), Config.milliSecondsToTimeOut, true); try { string requestFileName = Utils.RandomString(16).ToLower() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".stack"; // Write Request To file before detect FS.WriteCoinsToFile(coins, FS.RequestsFolder + requestFileName); await Task.WhenAll(tasks.AsParallel().Select(async task => await task())); int j = 0; foreach (var coin in coins) { coin.pown = ""; for (int k = 0; k < CloudCoinCore.Config.NodeCount; k++) { coin.response[k] = raida.nodes[k].MultiResponse.responses[j]; coin.pown += coin.response[k].outcome.Substring(0, 1); } int countp = coin.response.Where(x => x.outcome == "pass").Count(); int countf = coin.response.Where(x => x.outcome == "fail").Count(); coin.PassCount = countp; coin.FailCount = countf; CoinCount++; pge.MinorProgress = (CoinCount) * 100 / totalCoinCount; // Debug.WriteLine("Minor Progress- " + pge.MinorProgress); raida.OnProgressChanged(pge); coin.doPostProcessing(); j++; } pge.MinorProgress = (CoinCount - 1) * 100 / totalCoinCount; // Debug.WriteLine("Minor Progress- " + pge.MinorProgress); raida.OnProgressChanged(pge); FS.WriteCoin(coins, detectedLocation, true); FS.RemoveCoinsByFileName(coins, predetectLocation); FS.RemoveCoinsByFileName(coins, suspectLocation); //FS.WriteCoin(coins, FS.DetectedFolder); } catch (Exception ex) { // Debug.WriteLine(ex.Message); } } catch (Exception exx) { Console.WriteLine(exx.Message); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } //File.WriteAllText(lostFileName, ""); File.Delete(e.FullPath); } } }
public MainWindow() { showDisclaimer(); rootFolder = getWorkspace(); raida = RAIDA.GetInstance(); raida.FS = RAIDA.FileSystem = FS = new FileSystem(rootFolder); FS.CreateDirectories(); FS.LoadFileSystem(); logger = new SimpleLogger(FS.LogsFolder + "logs" + DateTime.Now.ToString("yyyyMMdd").ToLower() + ".log", true); fixer = new Frack_Fixer(FS, timeout); UpdateCELog(""); printStarLine(); UpdateCELog("Starting CloudCoin CE at " + DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss")); printStarLine(); SetupRAIDA(); RAIDA.window = this; InitializeComponent(); FS.CreateDirectories(); //loadJson(); printWelcome(); noteOne.NoteCount = "1"; noteFive.NoteCount = "5"; noteQtr.NoteCount = "10"; noteHundred.NoteCount = "100"; noteTwoFifty.NoteCount = "250"; raida1.IsActive = true; raida2.IsActive = true; raida3.IsActive = true; raida4.IsActive = true; raida5.IsActive = true; raida6.IsActive = true; raida7.IsActive = true; raida8.IsActive = true; raida9.IsActive = true; raida10.IsActive = true; raida11.IsActive = true; raida12.IsActive = true; raida13.IsActive = true; raida14.IsActive = true; raida15.IsActive = true; raida16.IsActive = true; raida17.IsActive = true; raida18.IsActive = true; raida19.IsActive = true; raida20.IsActive = true; raida21.IsActive = true; raida22.IsActive = true; raida23.IsActive = true; raida24.IsActive = true; raida25.IsActive = true; SetLEDFlashing(true); Echo(); ShowCoins(); new Thread(delegate() { Task.Delay(20000).ContinueWith(t => fix()); //fix(); }).Start(); resumeImport(); this.PreviewKeyDown += MainWindow_PreviewKeyDown; }
public async static Task ProcessNetworkCoins(int NetworkNumber, bool ChangeANS = true) { IFileSystem FS = FileSystem; FileSystem.LoadFileSystem(); FileSystem.DetectPreProcessing(); var predetectCoins = FS.LoadFolderCoins(FS.PreDetectFolder); predetectCoins = (from x in predetectCoins where x.nn == NetworkNumber select x).ToList(); IFileSystem.predetectCoins = predetectCoins; RAIDA raida = (from x in networks where x.NetworkNumber == NetworkNumber select x).FirstOrDefault(); if (raida == null) { return; } // Process Coins in Lots of 200. Can be changed from Config File int LotCount = predetectCoins.Count() / Config.MultiDetectLoad; if (predetectCoins.Count() % Config.MultiDetectLoad > 0) { LotCount++; } ProgressChangedEventArgs pge = new ProgressChangedEventArgs(); int CoinCount = 0; int totalCoinCount = predetectCoins.Count(); for (int i = 0; i < LotCount; i++) { //Pick up 200 Coins and send them to RAIDA var coins = predetectCoins.Skip(i * Config.MultiDetectLoad).Take(200); try { raida.coins = coins; } catch (Exception e) { Console.WriteLine(e.Message); } var tasks = raida.GetMultiDetectTasks(coins.ToArray(), Config.milliSecondsToTimeOut, ChangeANS); try { string requestFileName = Utils.RandomString(16).ToLower() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".stack"; // Write Request To file before detect FS.WriteCoinsToFile(coins, FS.RequestsFolder + requestFileName); await Task.WhenAll(tasks.AsParallel().Select(async task => await task())); int j = 0; foreach (var coin in coins) { coin.pown = ""; for (int k = 0; k < Config.NodeCount; k++) { coin.response[k] = raida.nodes[k].MultiResponse.responses[j]; coin.pown += coin.response[k].outcome.Substring(0, 1); } int countp = coin.response.Where(x => x.outcome == "pass").Count(); int countf = coin.response.Where(x => x.outcome == "fail").Count(); coin.PassCount = countp; coin.FailCount = countf; CoinCount++; updateLog("No. " + CoinCount + ". Coin Deteced. S. No. - " + coin.sn + ". Pass Count - " + coin.PassCount + ". Fail Count - " + coin.FailCount + ". Result - " + coin.DetectionResult + "." + coin.pown); Debug.WriteLine("Coin Deteced. S. No. - " + coin.sn + ". Pass Count - " + coin.PassCount + ". Fail Count - " + coin.FailCount + ". Result - " + coin.DetectionResult); //coin.sortToFolder(); pge.MinorProgress = (CoinCount) * 100 / totalCoinCount; Debug.WriteLine("Minor Progress- " + pge.MinorProgress); raida.OnProgressChanged(pge); j++; } pge.MinorProgress = (CoinCount - 1) * 100 / totalCoinCount; Debug.WriteLine("Minor Progress- " + pge.MinorProgress); raida.OnProgressChanged(pge); FS.WriteCoin(coins, FS.DetectedFolder); FS.RemoveCoins(coins, FS.PreDetectFolder); updateLog(pge.MinorProgress + " % of Coins on Network " + NetworkNumber + " processed."); //FS.WriteCoin(coins, FS.DetectedFolder); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } pge.MinorProgress = 100; Debug.WriteLine("Minor Progress- " + pge.MinorProgress); raida.OnProgressChanged(pge); var detectedCoins = FS.LoadFolderCoins(FS.DetectedFolder); //detectedCoins.ForEach(x => x.pown= "ppppppppppppppppppppppppp"); // Apply Sort to Folder to all detected coins at once. updateLog("Starting Sort....."); detectedCoins.ForEach(x => x.SortToFolder()); updateLog("Ended Sort........"); var passedCoins = (from x in detectedCoins where x.folder == FS.BankFolder select x).ToList(); var frackedCoins = (from x in detectedCoins where x.folder == FS.FrackedFolder select x).ToList(); var failedCoins = (from x in detectedCoins where x.folder == FS.CounterfeitFolder select x).ToList(); var lostCoins = (from x in detectedCoins where x.folder == FS.LostFolder select x).ToList(); var suspectCoins = (from x in detectedCoins where x.folder == FS.SuspectFolder select x).ToList(); Debug.WriteLine("Total Passed Coins - " + (passedCoins.Count() + frackedCoins.Count())); Debug.WriteLine("Total Failed Coins - " + failedCoins.Count()); updateLog("Coin Detection finished."); updateLog("Total Passed Coins - " + (passedCoins.Count() + frackedCoins.Count()) + ""); updateLog("Total Failed Coins - " + failedCoins.Count() + ""); updateLog("Total Lost Coins - " + lostCoins.Count() + ""); updateLog("Total Suspect Coins - " + suspectCoins.Count() + ""); // Move Coins to their respective folders after sort FS.MoveCoins(passedCoins, FS.DetectedFolder, FS.BankFolder); FS.MoveCoins(frackedCoins, FS.DetectedFolder, FS.FrackedFolder); //FS.WriteCoin(failedCoins, FS.CounterfeitFolder, true); FS.MoveCoins(lostCoins, FS.DetectedFolder, FS.LostFolder); FS.MoveCoins(suspectCoins, FS.DetectedFolder, FS.SuspectFolder); // Clean up Detected Folder FS.RemoveCoins(failedCoins, FS.DetectedFolder); FS.RemoveCoins(lostCoins, FS.DetectedFolder); FS.RemoveCoins(suspectCoins, FS.DetectedFolder); FS.MoveImportedFiles(); //after = DateTime.Now; //ts = after.Subtract(before); //Debug.WriteLine("Detection Completed in - " + ts.TotalMilliseconds / 1000); //updateLog("Detection Completed in - " + ts.TotalMilliseconds / 1000); pge.MinorProgress = 100; Debug.WriteLine("Minor Progress- " + pge.MinorProgress); }