/// <summary> /// Read config file. /// </summary> public static void ReadConfig() { if (File.Exists(GetCurrentPathFile())) { using (StreamReader reader = new StreamReader(GetCurrentPathFile())) { string line = string.Empty; while ((line = reader.ReadLine()) != null) { if (line.Contains("WALLET_ADDRESS=")) { Config.WalletAddress = line.Replace("WALLET_ADDRESS=", ""); } else if (line.Contains("PROXY_PORT=")) { Config.ProxyPort = int.Parse(line.Replace("PROXY_PORT=", "")); } else if (line.Contains("PROXY_IP=")) { Config.ProxyIP = line.Replace("PROXY_IP=", ""); } else if (line.Contains("WRITE_LOG=")) { string choose = line.Replace("WRITE_LOG=", "").ToLower(); if (choose == "y" || choose == "true") { Config.WriteLog = true; } } else if (line.Contains("ENABLE_API=")) { string choose = line.Replace("ENABLE_API=", "").ToLower(); if (choose == "y" || choose == "true") { Config.EnableApi = true; } } else if (line.Contains("API_PORT=")) { string choose = line.Replace("API_PORT=", "").ToLower(); if (int.TryParse(choose, out var port)) { if (port > 0) { Config.ProxyApiPort = port; } } } } } } else // First initialization { File.Create(GetCurrentPathFile()).Close(); ConsoleLog.WriteLine("No config.ini found, first initialization:", ClassConsoleColorEnumeration.IndexConsoleRedLog); ConsoleLog.WriteLine("Write your wallet address: ", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); Config.WalletAddress = Console.ReadLine(); ConsoleLog.WriteLine("Write an IP to bind [0.0.0.0 for listen on every network cards]: ", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); Config.ProxyIP = Console.ReadLine(); ConsoleLog.WriteLine("Select a port to bind: ", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); Config.ProxyPort = int.Parse(Console.ReadLine()); ConsoleLog.WriteLine("Do you want enable log system ? [Y/N]: ", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); string choose = Console.ReadLine(); if (choose.ToLower() == "y") { Config.WriteLog = true; } ConsoleLog.WriteLine("Do you want to enable the API system? [Y/N]: ", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); choose = Console.ReadLine(); if (choose.ToLower() == "y") { Config.EnableApi = true; } if (Config.EnableApi) { ConsoleLog.WriteLine("Then, do you want to select your own API port? [Default 8000]: ", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); choose = Console.ReadLine(); int port = 0; if (int.TryParse(choose, out port)) { Config.ProxyApiPort = port; } } using (StreamWriter writeConfig = new StreamWriter(GetCurrentPathFile()) { AutoFlush = true }) { writeConfig.WriteLine("WALLET_ADDRESS=" + Config.WalletAddress); writeConfig.WriteLine("PROXY_PORT=" + Config.ProxyPort); writeConfig.WriteLine("PROXY_IP=" + Config.ProxyIP); if (Config.WriteLog) { writeConfig.WriteLine("WRITE_LOG=Y"); } else { writeConfig.WriteLine("WRITE_LOG=N"); } if (Config.EnableApi) { writeConfig.WriteLine("ENABLE_API=Y"); writeConfig.WriteLine("API_PORT=" + Config.ProxyApiPort); } else { writeConfig.WriteLine("ENABLE_API=N"); writeConfig.WriteLine("API_PORT=" + Config.ProxyApiPort); } writeConfig.Close(); } } }
/// <summary> /// Execute command lines. /// </summary> /// <param name="command"></param> private static void CommandLine(string command) { switch (command) { case "h": ConsoleLog.WriteLine("h - Show command list.", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ConsoleLog.WriteLine("s - Show proxy stats with miners stats.", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); break; case "s": int totalMinerConnected = 0; if (NetworkBlockchain.ListMinerStats.Count > 0) { foreach (var minerStats in NetworkBlockchain.ListMinerStats) { if (minerStats.Value.MinerDifficultyStart == 0 && minerStats.Value.MinerDifficultyEnd == 0) { ConsoleLog.WriteLine("Miner name: " + minerStats.Key + " - Select range: Automatic - IP: " + minerStats.Value.MinerIp, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); } else { ConsoleLog.WriteLine("Miner name: " + minerStats.Key + " - Select range: " + minerStats.Value.MinerDifficultyStart + "|" + minerStats.Value.MinerDifficultyEnd + " - IP: " + minerStats.Value.MinerIp, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); } if (minerStats.Value.MinerConnectionStatus) { ConsoleLog.WriteLine("Miner status: Connected.", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); totalMinerConnected++; } else { ConsoleLog.WriteLine("Miner status: Disconnected.", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); } ConsoleLog.WriteLine("Miner total share: " + minerStats.Value.MinerTotalShare, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ConsoleLog.WriteLine("Miner total good share: " + minerStats.Value.MinerTotalGoodShare, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ConsoleLog.WriteLine("Miner total invalid share: " + minerStats.Value.MinerTotalInvalidShare, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ConsoleLog.WriteLine("Miner Hashrate Expected: " + minerStats.Value.MinerHashrateExpected, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ConsoleLog.WriteLine("Miner Hashrate Calculated from blocks found: " + minerStats.Value.MinerHashrateCalculated, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); string version = minerStats.Value.MinerVersion; if (string.IsNullOrEmpty(version)) { version = "Unknown"; } ConsoleLog.WriteLine("Miner version: " + version, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); } } if (NetworkBlockchain.IsConnected) { ConsoleLog.WriteLine("Network proxy connection to the network status: Connected.", ClassConsoleColorEnumeration.IndexConsoleGreenLog); } else { ConsoleLog.WriteLine("Network proxy connection to the network status: Disconnected.", ClassConsoleColorEnumeration.IndexConsoleRedLog); } ConsoleLog.WriteLine("Total miners connected: " + totalMinerConnected, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ConsoleLog.WriteLine(">> Invalid share can mean the share is invalid or already found.<<", ClassConsoleColorEnumeration.IndexConsoleYellowLog); ConsoleLog.WriteLine(">> Only total block unlocked confirmed counter retrieve you the right amount of blocks found.<<", ClassConsoleColorEnumeration.IndexConsoleYellowLog); ConsoleLog.WriteLine("Total block unlocked confirmed: " + NetworkBlockchain.TotalBlockUnlocked, ClassConsoleColorEnumeration.IndexConsoleGreenLog); ConsoleLog.WriteLine("Total block bad/orphan received: " + NetworkBlockchain.TotalBlockWrong, ClassConsoleColorEnumeration.IndexConsoleRedLog); break; } }
public static void Main(string[] args) { ProxyDateStart = DateTimeOffset.Now.ToUnixTimeSeconds(); Console.CancelKeyPress += Console_CancelKeyPress; ExceptionUnexpectedHandler(); Thread.CurrentThread.Name = Path.GetFileName(Environment.GetCommandLineArgs()[0]); ConsoleLog.WriteLine("Xiropht Proxy Solo Miner - " + Assembly.GetExecutingAssembly().GetName().Version + "R", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ReadConfig(); if (Config.WriteLog) { ConsoleLog.InitializeLog(); ConsoleLog.WriteLine("Write Log Enabled.", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); } ConsoleLog.WriteLine("Wallet Address selected: " + Config.WalletAddress, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ConsoleLog.WriteLine("Proxy IP Selected: " + Config.ProxyIP, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ConsoleLog.WriteLine("Proxy Port Selected: " + Config.ProxyPort, ClassConsoleColorEnumeration.IndexConsoleMagentaLog); if (Config.EnableApi) { ConsoleLog.WriteLine("Start HTTP API..", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); ClassApi.StartApiHttpServer(); ConsoleLog.WriteLine("HTTP API started.", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); } ThreadCheckNetworkConnection = new Thread(async delegate() { bool connectSuccess = false; while (!connectSuccess) { while (!await NetworkBlockchain.ConnectToBlockchainAsync()) { ConsoleLog.WriteLine("Can't connect to the network, retry in 5 seconds..", ClassConsoleColorEnumeration.IndexConsoleMagentaLog); Thread.Sleep(5000); } ConsoleLog.WriteLine("Connection success, generate dynamic certificate for the network.", ClassConsoleColorEnumeration.IndexConsoleGreenLog); NetworkCertificate = ClassUtils.GenerateCertificate(); ConsoleLog.WriteLine("Certificate generate, send to the network..", ClassConsoleColorEnumeration.IndexConsoleYellowLog); if (!await NetworkBlockchain.SendPacketAsync(NetworkCertificate, false)) { ConsoleLog.WriteLine("Can't send certificate, reconnect now..", ClassConsoleColorEnumeration.IndexConsoleRedLog); } else { ConsoleLog.WriteLine("Certificate sent, start to login..", ClassConsoleColorEnumeration.IndexConsoleYellowLog); NetworkBlockchain.ListenBlockchain(); Thread.Sleep(1000); if (!await NetworkBlockchain.SendPacketAsync(ClassConnectorSettingEnumeration.MinerLoginType + "|" + Config.WalletAddress, true)) { ConsoleLog.WriteLine("Can't login to the network, reconnect now.", ClassConsoleColorEnumeration.IndexConsoleRedLog); } else { ConsoleLog.WriteLine("Login successfully sent, waiting confirmation..", ClassConsoleColorEnumeration.IndexConsoleYellowLog); connectSuccess = true; } } } }); ThreadCheckNetworkConnection.Start(); ThreadProxyCommandLine = new Thread(delegate() { while (true) { string commandLine = GetHiddenConsoleInput(); CommandLine(commandLine); } }); ThreadProxyCommandLine.Start(); }
/// <summary> /// Event for detect Cancel Key pressed by the user for close the program. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; ConsoleLog.WriteLine("Close proxy solo miner tool.", ClassConsoleColorEnumeration.IndexConsoleRedLog); Process.GetCurrentProcess().Kill(); }
private static void CheckBlockchainConnection() { _lastPacketReceivedFromBlockchain = DateTimeOffset.Now.ToUnixTimeSeconds(); var threadCheckConnection = new Thread(async delegate() { while (true) { Thread.Sleep(1000); if (!IsConnected || !classSeedNodeConnector.ReturnStatus()) { if (ThreadListenBlockchain != null && (ThreadListenBlockchain.IsAlive || ThreadListenBlockchain != null)) { ThreadListenBlockchain.Abort(); GC.SuppressFinalize(ThreadListenBlockchain); } if (ThreadAskMiningMethod != null && (ThreadAskMiningMethod.IsAlive || ThreadAskMiningMethod != null)) { ThreadAskMiningMethod.Abort(); GC.SuppressFinalize(ThreadAskMiningMethod); } IsConnected = false; LoginAccepted = false; NetworkProxy.StopProxy(); while (!await ConnectToBlockchainAsync()) { ConsoleLog.WriteLine("Can't connect to the network, retry in 5 seconds..", ClassConsoleColorEnumeration.IndexConsoleRedLog); Thread.Sleep(5000); } ConsoleLog.WriteLine("Connection success, generate dynamic certificate for the network.", ClassConsoleColorEnumeration.IndexConsoleGreenLog); Program.NetworkCertificate = ClassUtils.GenerateCertificate(); ConsoleLog.WriteLine("Certificate generate, send to the network..", ClassConsoleColorEnumeration.IndexConsoleYellowLog); if (!await SendPacketAsync(Program.NetworkCertificate, false)) { ConsoleLog.WriteLine("Can't send certificate, reconnect now..", ClassConsoleColorEnumeration.IndexConsoleRedLog); IsConnected = false; } else { Thread.Sleep(1000); ConsoleLog.WriteLine("Certificate sent, start to login..", ClassConsoleColorEnumeration.IndexConsoleYellowLog); ListenBlockchain(); if (!await SendPacketAsync(ClassConnectorSettingEnumeration.MinerLoginType + "|" + Config.WalletAddress, true)) { ConsoleLog.WriteLine("Can't login to the network, reconnect now.", ClassConsoleColorEnumeration.IndexConsoleRedLog); IsConnected = false; } else { ConsoleLog.WriteLine("Login successfully sent, waiting confirmation.. (Wait 5 seconds maximum.)", ClassConsoleColorEnumeration.IndexConsoleYellowLog); IsConnected = true; Thread.Sleep(ClassConnectorSetting.MaxTimeoutConnect); if (!LoginAccepted) { IsConnected = false; } } } } } }); threadCheckConnection.Start(); }
/// <summary> /// Spread job range to miners. /// </summary> /// <param name="minerId"></param> public static async void SpreadJobAsync(int minerId = -1) { try { var splitBlockContent = Blocktemplate.Split(new[] { "&" }, StringSplitOptions.None); CurrentBlockId = splitBlockContent[0].Replace("ID=", ""); if (FirstBlockId == 0) { int.TryParse(CurrentBlockId, out FirstBlockId); } if (CurrentBlockId != "" && CurrentBlockId.Length > 0) { CurrentBlockHash = splitBlockContent[1].Replace("HASH=", ""); CurrentBlockAlgorithm = splitBlockContent[2].Replace("ALGORITHM=", ""); CurrentBlockSize = splitBlockContent[3].Replace("SIZE=", ""); CurrentBlockMethod = splitBlockContent[4].Replace("METHOD=", ""); CurrentBlockKey = splitBlockContent[5].Replace("KEY=", ""); CurrentBlockJob = splitBlockContent[6].Replace("JOB=", ""); CurrentBlockReward = splitBlockContent[7].Replace("REWARD=", ""); CurrentBlockDifficulty = splitBlockContent[8].Replace("DIFFICULTY=", ""); CurrentBlockTimestampCreate = splitBlockContent[9].Replace("TIMESTAMP=", ""); CurrentBlockIndication = splitBlockContent[10].Replace("INDICATION=", ""); var splitCurrentBlockJob = CurrentBlockJob.Split(new[] { ";" }, StringSplitOptions.None); var minRange = decimal.Parse(splitCurrentBlockJob[0]); var maxRange = decimal.Parse(splitCurrentBlockJob[1]); if (ListMinerStats != null) { int totalMinerConnected = 0; foreach (var minerStats in ListMinerStats) { if (minerStats.Value.MinerConnectionStatus) { totalMinerConnected++; } } int i1 = 0; if (minerId != -1) { for (int i = 0; i < NetworkProxy.ListOfMiners.Count; i++) { if (i < NetworkProxy.ListOfMiners.Count) { try { if (NetworkProxy.ListOfMiners[i] != null) { if (NetworkProxy.ListOfMiners[i].MinerConnected) { if (NetworkProxy.ListOfMiners[i].MinerInitialized) { if (ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyStart <= 0 && ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyEnd <= 0) { i1++; if (NetworkProxy.ListOfMiners[i].MinerId == minerId) { var minRangeTmp = (decimal)Math.Round((maxRange / totalMinerConnected) * (i1 - 1), 0); var maxRangeTmp = (decimal)(Math.Round(((maxRange / totalMinerConnected) * i1), 0)); if (minRangeTmp < minRange) { minRangeTmp = minRange; } var blocktemplateTmp = "ID=" + CurrentBlockId + "&HASH=" + CurrentBlockHash + "&ALGORITHM=" + CurrentBlockAlgorithm + "&SIZE=" + CurrentBlockSize + "&METHOD=" + CurrentBlockMethod + "&KEY=" + CurrentBlockKey + "&JOB=" + minRangeTmp + ";" + maxRangeTmp + "&REWARD=" + CurrentBlockReward + "&DIFFICULTY=" + CurrentBlockDifficulty + "&TIMESTAMP=" + CurrentBlockTimestampCreate + "&INDICATION=" + CurrentBlockIndication + "&PROXY=YES"; ConsoleLog.WriteLine("Send job: " + minRangeTmp + "/" + maxRangeTmp + " range to miner: " + NetworkProxy.ListOfMiners[i].MinerName, ClassConsoleColorEnumeration.IndexConsoleYellowLog); if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendCurrentBlockMining + "|" + blocktemplateTmp).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].MinerInitialized = false; NetworkProxy.ListOfMiners[i].MinerConnected = false; try { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } catch { } NetworkProxy.ListOfMiners[i] = null; } else { ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerLastBlockTemplateReceived = DateTimeOffset.Now.ToUnixTimeSeconds(); } } } else { if (NetworkProxy.ListOfMiners[i].MinerId == minerId) { ConsoleLog.WriteLine(NetworkProxy.ListOfMiners[i].MinerName + " select start position range: " + ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyStart + " | select end position range: " + ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyEnd, ClassConsoleColorEnumeration.IndexConsoleYellowLog); var minerJobRangePosition = ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyStart; var minerJobRangePourcentage = ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyEnd; if (minerJobRangePourcentage <= 0) { minerJobRangePourcentage = 100; } if (minerJobRangePosition > 100) { minerJobRangePosition = 100; } var minerJobRangePositionStart = (maxRange * minerJobRangePosition) / 100; var minerJobRangePositionEnd = (maxRange * minerJobRangePourcentage) / 100; if (minerJobRangePositionEnd <= minerJobRangePositionStart) { minerJobRangePositionEnd = minerJobRangePositionEnd + minerJobRangePositionStart; } var minRangeTmp = (decimal)Math.Round(minerJobRangePositionStart, 0); var maxRangeTmp = (decimal)Math.Round(minerJobRangePositionEnd, 0); if (minRangeTmp < minRange) { minRangeTmp = minRange; } var blocktemplateTmp = "ID=" + CurrentBlockId + "&HASH=" + CurrentBlockHash + "&ALGORITHM=" + CurrentBlockAlgorithm + "&SIZE=" + CurrentBlockSize + "&METHOD=" + CurrentBlockMethod + "&KEY=" + CurrentBlockKey + "&JOB=" + minRangeTmp + ";" + maxRangeTmp + "&REWARD=" + CurrentBlockReward + "&DIFFICULTY=" + CurrentBlockDifficulty + "&TIMESTAMP=" + CurrentBlockTimestampCreate + "&INDICATION=" + CurrentBlockIndication + "&PROXY=YES"; ConsoleLog.WriteLine("Send job: " + minRangeTmp + "/" + maxRangeTmp + " range to miner: " + NetworkProxy.ListOfMiners[i].MinerName, ClassConsoleColorEnumeration.IndexConsoleYellowLog); if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendCurrentBlockMining + "|" + blocktemplateTmp).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].MinerInitialized = false; NetworkProxy.ListOfMiners[i].MinerConnected = false; try { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } catch { } NetworkProxy.ListOfMiners[i] = null; } else { ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerLastBlockTemplateReceived = DateTimeOffset.Now.ToUnixTimeSeconds(); } } } } } } } catch { } } } } else { for (int i = 0; i < NetworkProxy.ListOfMiners.Count; i++) { if (i < NetworkProxy.ListOfMiners.Count) { try { if (NetworkProxy.ListOfMiners[i] != null) { if (NetworkProxy.ListOfMiners[i].MinerConnected) { if (NetworkProxy.ListOfMiners[i].MinerInitialized) { if (ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyStart <= 0 && ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyEnd <= 0) { i1++; var minRangeTmp = (decimal)Math.Round((maxRange / totalMinerConnected) * (i1 - 1), 0); var maxRangeTmp = (decimal)(Math.Round(((maxRange / totalMinerConnected) * i1), 0)); if (minRangeTmp < minRange) { minRangeTmp = minRange; } var blocktemplateTmp = "ID=" + CurrentBlockId + "&HASH=" + CurrentBlockHash + "&ALGORITHM=" + CurrentBlockAlgorithm + "&SIZE=" + CurrentBlockSize + "&METHOD=" + CurrentBlockMethod + "&KEY=" + CurrentBlockKey + "&JOB=" + minRangeTmp + ";" + maxRangeTmp + "&REWARD=" + CurrentBlockReward + "&DIFFICULTY=" + CurrentBlockDifficulty + "&TIMESTAMP=" + CurrentBlockTimestampCreate + "&INDICATION=" + CurrentBlockIndication + "&PROXY=YES"; ConsoleLog.WriteLine("Send job: " + minRangeTmp + "/" + maxRangeTmp + " range to miner: " + NetworkProxy.ListOfMiners[i].MinerName, ClassConsoleColorEnumeration.IndexConsoleYellowLog); if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendCurrentBlockMining + "|" + blocktemplateTmp).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].MinerInitialized = false; NetworkProxy.ListOfMiners[i].MinerConnected = false; try { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } catch { } NetworkProxy.ListOfMiners[i] = null; } else { ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerLastBlockTemplateReceived = DateTimeOffset.Now.ToUnixTimeSeconds(); } } else { ConsoleLog.WriteLine(NetworkProxy.ListOfMiners[i].MinerName + " select start position range: " + ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyStart + " | select end position range: " + ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyEnd, ClassConsoleColorEnumeration.IndexConsoleYellowLog); var minerJobRangePosition = ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyStart; var minerJobRangePourcentage = ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerDifficultyEnd; if (minerJobRangePourcentage <= 0) { minerJobRangePourcentage = 100; } if (minerJobRangePosition > 100) { minerJobRangePosition = 100; } var minerJobRangePositionStart = (maxRange * minerJobRangePosition) / 100; var minerJobRangePositionEnd = (maxRange * minerJobRangePourcentage) / 100; if (minerJobRangePositionEnd <= minerJobRangePositionStart) { minerJobRangePositionEnd = minerJobRangePositionEnd + minerJobRangePositionStart; } var minRangeTmp = (decimal)Math.Round(minerJobRangePositionStart, 0); var maxRangeTmp = (decimal)Math.Round(minerJobRangePositionEnd, 0); if (minRangeTmp < minRange) { minRangeTmp = minRange; } var blocktemplateTmp = "ID=" + CurrentBlockId + "&HASH=" + CurrentBlockHash + "&ALGORITHM=" + CurrentBlockAlgorithm + "&SIZE=" + CurrentBlockSize + "&METHOD=" + CurrentBlockMethod + "&KEY=" + CurrentBlockKey + "&JOB=" + minRangeTmp + ";" + maxRangeTmp + "&REWARD=" + CurrentBlockReward + "&DIFFICULTY=" + CurrentBlockDifficulty + "&TIMESTAMP=" + CurrentBlockTimestampCreate + "&INDICATION=" + CurrentBlockIndication + "&PROXY=YES"; ConsoleLog.WriteLine("Send job: " + minRangeTmp + "/" + maxRangeTmp + " range to miner: " + NetworkProxy.ListOfMiners[i].MinerName, ClassConsoleColorEnumeration.IndexConsoleYellowLog); if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendCurrentBlockMining + "|" + blocktemplateTmp).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].MinerInitialized = false; NetworkProxy.ListOfMiners[i].MinerConnected = false; try { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } catch { } NetworkProxy.ListOfMiners[i] = null; } else { ListMinerStats[NetworkProxy.ListOfMiners[i].MinerName].MinerLastBlockTemplateReceived = DateTimeOffset.Now.ToUnixTimeSeconds(); } } } } } } catch { } } } } } } } catch (Exception error) { FastWriteExceptionError(error); if (NetworkProxy.ListOfMiners.Count > 0) { for (int i = 0; i < NetworkProxy.ListOfMiners.Count; i++) { if (i < NetworkProxy.ListOfMiners.Count) { if (NetworkProxy.ListOfMiners[i] != null) { try { if (NetworkProxy.ListOfMiners[i].MinerConnected) { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } } catch { } } } } } } }
/// <summary> /// Receive packet from the blockchain. /// </summary> /// <param name="packet"></param> private static async Task <bool> HandlePacketBlockchainAsync(string packet) { var splitPacket = packet.Split(new[] { "|" }, StringSplitOptions.None); switch (splitPacket[0]) { case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendLoginAccepted: LoginAccepted = true; IsConnected = true; ConsoleLog.WriteLine("Proxy login accepted, ask mining methods.", ClassConsoleColorEnumeration.IndexConsoleGreenLog); if (!NetworkProxy.ProxyStarted) { NetworkProxy.StartProxy(); } AskMiningMethod(); break; case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendListBlockMethod: var methodList = splitPacket[1]; if (methodList.Contains("#")) { var splitMethodList = methodList.Split(new[] { "#" }, StringSplitOptions.None); if (ListOfMiningMethodName.Count > 1) { foreach (var methodName in splitMethodList) { if (!string.IsNullOrEmpty(methodName)) { if (ListOfMiningMethodName.Contains(methodName) == false) { ListOfMiningMethodName.Add(methodName); } if (!await classSeedNodeConnector.SendPacketToSeedNodeAsync(ClassSoloMiningPacketEnumeration.SoloMiningSendPacketEnumeration.ReceiveAskContentBlockMethod + "|" + methodName, Program.NetworkCertificate, false, true).ConfigureAwait(false)) { return(false); } await Task.Delay(1000); } } } else { foreach (var methodName in splitMethodList) { if (!string.IsNullOrEmpty(methodName)) { if (ListOfMiningMethodName.Contains(methodName) == false) { ListOfMiningMethodName.Add(methodName); } if (!await classSeedNodeConnector.SendPacketToSeedNodeAsync(ClassSoloMiningPacketEnumeration.SoloMiningSendPacketEnumeration.ReceiveAskContentBlockMethod + "|" + methodName, Program.NetworkCertificate, false, true).ConfigureAwait(false)) { return(false); } await Task.Delay(1000); } } } } else { if (ListOfMiningMethodName.Contains(methodList) == false) { ListOfMiningMethodName.Add(methodList); } if (!await classSeedNodeConnector.SendPacketToSeedNodeAsync(ClassSoloMiningPacketEnumeration.SoloMiningSendPacketEnumeration.ReceiveAskContentBlockMethod + "|" + methodList, Program.NetworkCertificate, false, true).ConfigureAwait(false)) { return(false); } } break; case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendContentBlockMethod: if (ListOfMiningMethodContent.Count == 0) { ListOfMiningMethodContent.Add(splitPacket[1]); } else { ListOfMiningMethodContent[0] = splitPacket[1]; } break; case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendCurrentBlockMining: var splitBlockContent = splitPacket[1].Split(new[] { "&" }, StringSplitOptions.None); if (Blocktemplate != splitPacket[1]) { ConsoleLog.WriteLine("New block to mining: " + splitBlockContent[0], ClassConsoleColorEnumeration.IndexConsoleYellowLog); Blocktemplate = splitPacket[1]; await Task.Factory.StartNew(() => SpreadJobAsync(), CancellationToken.None, TaskCreationOptions.RunContinuationsAsynchronously, TaskScheduler.Current).ConfigureAwait(false); } break; case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendJobStatus: switch (splitPacket[1]) { case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareUnlock: TotalBlockUnlocked++; ConsoleLog.WriteLine("Block accepted, stop mining, wait new block.", ClassConsoleColorEnumeration.IndexConsoleGreenLog); for (int i = 0; i < NetworkProxy.ListOfMiners.Count; i++) { if (i < NetworkProxy.ListOfMiners.Count) { if (NetworkProxy.ListOfMiners[i].MinerConnected) { if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendJobStatus + "|" + ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareUnlock).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } } } } break; case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareWrong: for (int i = 0; i < NetworkProxy.ListOfMiners.Count; i++) { if (i < NetworkProxy.ListOfMiners.Count) { if (NetworkProxy.ListOfMiners[i].MinerConnected) { if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendJobStatus + "|" + ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareWrong).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } } } } TotalBlockWrong++; ConsoleLog.WriteLine("Block not accepted, stop mining, wait new block.", ClassConsoleColorEnumeration.IndexConsoleRedLog); break; case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareBad: for (int i = 0; i < NetworkProxy.ListOfMiners.Count; i++) { if (i < NetworkProxy.ListOfMiners.Count) { if (NetworkProxy.ListOfMiners[i].MinerConnected) { if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendJobStatus + "|" + ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareBad).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } } } } TotalBlockWrong++; ConsoleLog.WriteLine("Block not accepted, stop mining, wait new block.", ClassConsoleColorEnumeration.IndexConsoleRedLog); break; case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareAleady: for (int i = 0; i < NetworkProxy.ListOfMiners.Count; i++) { if (i < NetworkProxy.ListOfMiners.Count) { if (NetworkProxy.ListOfMiners[i].MinerConnected) { if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendJobStatus + "|" + ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareBad).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } } } } ConsoleLog.WriteLine("Block already mined, stop mining, wait new block.", ClassConsoleColorEnumeration.IndexConsoleRedLog); break; case ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareNotExist: for (int i = 0; i < NetworkProxy.ListOfMiners.Count; i++) { if (i < NetworkProxy.ListOfMiners.Count) { if (NetworkProxy.ListOfMiners[i].MinerConnected) { if (!await NetworkProxy.ListOfMiners[i].SendPacketAsync(ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.SendJobStatus + "|" + ClassSoloMiningPacketEnumeration.SoloMiningRecvPacketEnumeration.ShareNotExist).ConfigureAwait(false)) { NetworkProxy.ListOfMiners[i].DisconnectMiner(); } } } } ConsoleLog.WriteLine("Block mined not exist, stop mining, wait new block.", ClassConsoleColorEnumeration.IndexConsoleBlueLog); break; } break; } return(true); }
/// <summary> /// Listen Blockchain packet. /// </summary> public static void ListenBlockchain() { if (ThreadListenBlockchain != null && (ThreadListenBlockchain.IsAlive || ThreadListenBlockchain != null)) { ThreadListenBlockchain.Abort(); GC.SuppressFinalize(ThreadListenBlockchain); } ThreadListenBlockchain = new Thread(async delegate() { while (IsConnected) { try { using (CancellationTokenSource cancellation = new CancellationTokenSource(100)) { string packet = await classSeedNodeConnector.ReceivePacketFromSeedNodeAsync(Program.NetworkCertificate, false, true); if (packet == ClassSeedNodeStatus.SeedError) { ConsoleLog.WriteLine("Connection to network lost, reconnect in 5 seconds..", ClassConsoleColorEnumeration.IndexConsoleRedLog); IsConnected = false; break; } _lastPacketReceivedFromBlockchain = DateTimeOffset.Now.ToUnixTimeSeconds(); if (packet.Contains("*")) { var splitPacket = packet.Split(new[] { "*" }, StringSplitOptions.None); if (splitPacket.Length > 1) { foreach (var packetEach in splitPacket) { if (packetEach != null) { if (!string.IsNullOrEmpty(packetEach)) { if (!await HandlePacketBlockchainAsync(packetEach.Replace("*", ""))) { IsConnected = false; } } } } } else { if (!await HandlePacketBlockchainAsync(packet.Replace("*", ""))) { IsConnected = false; } } } else { if (!await HandlePacketBlockchainAsync(packet)) { IsConnected = false; } } } } catch { ConsoleLog.WriteLine("Connection to network lost, reconnect in 5 seconds..", ClassConsoleColorEnumeration.IndexConsoleRedLog); IsConnected = false; break; } } }); ThreadListenBlockchain.Start(); }