ConsolePrint() public static method

public static ConsolePrint ( string grp, string text ) : void
grp string
text string
return void
Beispiel #1
0
        private StartMiningReturnType StartMining(bool showWarnings)
        {
            if (textBoxBTCAddress.Text.Equals(""))
            {
                if (showWarnings)
                {
                    var result = MessageBox.Show(International.GetText("Form_Main_DemoModeMsg"),
                                                 International.GetText("Form_Main_DemoModeTitle"),
                                                 MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (result == DialogResult.Yes)
                    {
                        _demoMode             = true;
                        labelDemoMode.Visible = true;
                        labelDemoMode.Text    = International.GetText("Form_Main_DemoModeLabel");
                    }
                    else
                    {
                        return(StartMiningReturnType.IgnoreMsg);
                    }
                }
                else
                {
                    return(StartMiningReturnType.IgnoreMsg);
                }
            }
            else if (!VerifyMiningAddress(true))
            {
                return(StartMiningReturnType.IgnoreMsg);
            }

            var hasData = NHSmaData.HasData;

            if (!showWarnings)
            {
                for (var i = 0; i < 10; i++)
                {
                    if (hasData)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                    hasData = NHSmaData.HasData;
                    Helpers.ConsolePrint("NICEHASH", $"After {i}s has data: {hasData}");
                }
            }

            if (!hasData)
            {
                Helpers.ConsolePrint("NICEHASH", "No data received within timeout");
                if (showWarnings)
                {
                    MessageBox.Show(International.GetText("Form_Main_msgbox_NullNiceHashDataMsg"),
                                    International.GetText("Error_with_Exclamation"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return(StartMiningReturnType.IgnoreMsg);
            }


            // Check if there are unbenchmakred algorithms
            var isBenchInit = true;

            foreach (var cdev in ComputeDeviceManager.Available.Devices)
            {
                if (cdev.Enabled)
                {
                    if (cdev.GetAlgorithmSettings().Where(algo => algo.Enabled).Any(algo => algo.BenchmarkSpeed == 0))
                    {
                        isBenchInit = false;
                    }
                }
            }
            // Check if the user has run benchmark first
            if (!isBenchInit)
            {
                var result = DialogResult.No;
                if (showWarnings)
                {
                    result = MessageBox.Show(International.GetText("EnabledUnbenchmarkedAlgorithmsWarning"),
                                             International.GetText("Warning_with_Exclamation"),
                                             MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                }
                if (result == DialogResult.Yes)
                {
                    _benchmarkForm = new Form_Benchmark(
                        BenchmarkPerformanceType.Standard,
                        true);
                    SetChildFormCenter(_benchmarkForm);
                    _benchmarkForm.ShowDialog();
                    _benchmarkForm = null;
                    InitMainConfigGuiData();
                }
                else if (result == DialogResult.No)
                {
                    // check devices without benchmarks
                    foreach (var cdev in ComputeDeviceManager.Available.Devices)
                    {
                        if (cdev.Enabled)
                        {
                            var enabled = cdev.GetAlgorithmSettings().Any(algo => algo.BenchmarkSpeed > 0);
                            cdev.Enabled = enabled;
                        }
                    }
                }
                else
                {
                    return(StartMiningReturnType.IgnoreMsg);
                }
            }

            textBoxBTCAddress.Enabled = false;
            textBoxWorkerName.Enabled = false;
            comboBoxLocation.Enabled  = false;
            buttonBenchmark.Enabled   = false;
            buttonStartMining.Enabled = false;
            buttonSettings.Enabled    = false;
            devicesListViewEnableControl1.IsMining = true;
            buttonStopMining.Enabled = true;

            // Disable profitable notification on start
            _isNotProfitable = false;

            ConfigManager.GeneralConfig.BitcoinAddress  = textBoxBTCAddress.Text.Trim();
            ConfigManager.GeneralConfig.WorkerName      = textBoxWorkerName.Text.Trim();
            ConfigManager.GeneralConfig.ServiceLocation = comboBoxLocation.SelectedIndex;

            InitFlowPanelStart();
            ClearRatesAll();

            var btcAdress = _demoMode ? Globals.DemoUser : textBoxBTCAddress.Text.Trim();
            var isMining  = MinersManager.StartInitialize(this, Globals.MiningLocation[comboBoxLocation.SelectedIndex],
                                                          textBoxWorkerName.Text.Trim(), btcAdress);

            if (!_demoMode)
            {
                ConfigManager.GeneralConfigFileCommit();
            }

            //_isSmaUpdated = true; // Always check profits on mining start
            //_smaMinerCheck.Interval = 100;
            //_smaMinerCheck.Start();
            _minerStatsCheck.Start();

            if (ConfigManager.GeneralConfig.RunScriptOnCUDA_GPU_Lost)
            {
                _computeDevicesCheckTimer          = new SystemTimer();
                _computeDevicesCheckTimer.Elapsed += ComputeDevicesCheckTimer_Tick;
                _computeDevicesCheckTimer.Interval = 60000;

                _computeDevicesCheckTimer.Start();
            }

            return(isMining ? StartMiningReturnType.StartMining : StartMiningReturnType.ShowNoMining);
        }
Beispiel #2
0
 private static void CloseCallback(object sender, CloseEventArgs e)
 {
     Helpers.ConsolePrint("SOCKET", $"Connection closed code {e.Code}: {e.Reason}");
     AttemptReconnect();
 }
Beispiel #3
0
        virtual protected NiceHashProcess _Start()
        {
            // never start when ended
            if (isEnded)
            {
                return(null);
            }

            PreviousTotalMH = 0.0;
            if (LastCommandLine.Length == 0)
            {
                return(null);
            }

            NiceHashProcess P = new NiceHashProcess();

            if (WorkingDirectory.Length > 1)
            {
                P.StartInfo.WorkingDirectory = WorkingDirectory;
            }
            if (MinersSettingsManager.MinerSystemVariables.ContainsKey(Path))
            {
                foreach (var kvp in MinersSettingsManager.MinerSystemVariables[Path])
                {
                    string envName  = kvp.Key;
                    string envValue = kvp.Value;
                    P.StartInfo.EnvironmentVariables[envName] = envValue;
                }
            }

            P.StartInfo.FileName = Path;
            P.ExitEvent          = Miner_Exited;

            P.StartInfo.Arguments = LastCommandLine;
            if (IsNeverHideMiningWindow)
            {
                P.StartInfo.CreateNoWindow = false;
                if (ConfigManager.GeneralConfig.HideMiningWindows || ConfigManager.GeneralConfig.MinimizeMiningWindows)
                {
                    P.StartInfo.WindowStyle     = ProcessWindowStyle.Minimized;
                    P.StartInfo.UseShellExecute = true;
                }
            }
            else
            {
                P.StartInfo.CreateNoWindow = ConfigManager.GeneralConfig.HideMiningWindows;
            }
            P.StartInfo.UseShellExecute = false;

            try
            {
                if (P.Start())
                {
                    IsRunning = true;

                    _currentPidData = new MinerPID_Data();
                    _currentPidData.minerBinPath = P.StartInfo.FileName;
                    _currentPidData.PID          = P.Id;
                    _allPidData.Add(_currentPidData);

                    Helpers.ConsolePrint(MinerTAG(), "Starting miner " + ProcessTag() + " " + LastCommandLine);

                    StartCoolDownTimerChecker();

                    return(P);
                }
                else
                {
                    Helpers.ConsolePrint(MinerTAG(), "NOT STARTED " + ProcessTag() + " " + LastCommandLine);
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " _Start: " + ex.Message);
                return(null);
            }
        }
        private void BenchmarkBtn_Click(object sender, EventArgs e)
        {
            if (InBenchmark)
            {
                mm.BenchmarkSignalQuit = true;
                InBenchmark            = false;
                index = 9999;
                return;
            }

            bool   DeviceChecked = false;
            string DeviceName    = "";

            for (int i = 0; i < DevicesListView.Items.Count; i++)
            {
                if (DevicesListView.Items[i].Selected)
                {
                    DeviceChecked = true;
                    Int32.TryParse(DevicesListView.Items[i].SubItems[2].Text, out DeviceChecked_Index);

                    mm         = DevicesListView.Items[i].Tag as Miner;
                    DeviceName = DevicesListView.Items[i].SubItems[1].Text;
                }
            }

            if (!DeviceChecked)
            {
                MessageBox.Show(International.GetText("SubmitResultDialog_NoDeviceCheckedMsg"),
                                International.GetText("SubmitResultDialog_NoDeviceCheckedTitle"),
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            InBenchmark                  = true;
            DevicesListView.Enabled      = false;
            CloseBtn.Enabled             = false;
            StartStopBtn.Text            = International.GetText("SubmitResultDialog_StopBtn");
            LabelProgressPercentage.Text = "0.00%";
            index = 0;

            Helpers.ConsolePrint("SubmitResultDialog", "Number of Devices: " + mm.CDevs.Count);
            if (mm.CDevs.Count == 1 && mm.CountBenchmarkedAlgos() != 0)
            {
                DialogResult result = MessageBox.Show(International.GetText("SubmitResultDialog_UsePreviousBenchmarkedValueMsg"),
                                                      International.GetText("SubmitResultDialog_UsePreviousBenchmarkedValueTitle"),
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    index = 9999;
                }
            }

            // Temporarily disable the other ComputeDevices in the same Group
            for (int i = 0; i < mm.CDevs.Count; i++)
            {
                if (mm.CDevs[i].ID != DeviceChecked_Index)
                {
                    mm.CDevs[i].Enabled = false;
                }
                else
                {
                    mm.CDevs[i].Enabled = true;
                }
            }

            BenchmarkProgressBar.Maximum = mm.SupportedAlgorithms.Length;

            // Parse GPU name
            Helpers.ConsolePrint("SubmitResultDialog", "Old DeviceName: " + DeviceName);
            if (DeviceName.Contains("GeForce") || DeviceName.Contains("GTX") || DeviceName.Contains("GT"))
            {
                string [] DeviceNameSplit = DeviceName.Split(' ');

                for (int i = 0; i < DeviceNameSplit.Length; i++)
                {
                    Helpers.ConsolePrint("DEBUG", "DeviceNameSplit[" + i + "]: " + DeviceNameSplit[i]);

                    if (DeviceNameSplit[i].Equals("GT") || DeviceNameSplit[i].Equals("GTX"))
                    {
                        if ((i + 2) <= DeviceNameSplit.Length)
                        {
                            DeviceName = "NVIDIA " + DeviceNameSplit[i] + DeviceNameSplit[i + 1];
                            for (int j = i + 2; j < DeviceNameSplit.Length; j++)
                            {
                                DeviceName += " " + DeviceNameSplit[j];
                            }

                            break;
                        }
                    }
                }
            }
            Helpers.ConsolePrint("SubmitResultDialog", "New DeviceName: " + DeviceName);

            url = "https://www.nicehash.com/?p=calc&name=" + DeviceName;
            InitiateBenchmark();
        }
Beispiel #5
0
        /// <summary>
        /// Thread routine for miners that cannot be scheduled to stop and need speed data read from command line
        /// </summary>
        /// <param name="commandLine"></param>
        /// <param name="benchmarkTimeWait"></param>
        protected void BenchmarkThreadRoutineAlternate(object commandLine, int benchmarkTimeWait)
        {
            CleanAllOldLogs();

            Thread.Sleep(ConfigManager.GeneralConfig.MinerRestartDelayMS);

            BenchmarkSignalQuit      = false;
            BenchmarkSignalHanged    = false;
            BenchmarkSignalFinnished = false;
            BenchmarkException       = null;

            try {
                Helpers.ConsolePrint("BENCHMARK", "Benchmark starts");
                Helpers.ConsolePrint(MinerTAG(), "Benchmark should end in : " + benchmarkTimeWait + " seconds");
                BenchmarkHandle = BenchmarkStartProcess((string)commandLine);
                BenchmarkHandle.WaitForExit(benchmarkTimeWait + 2);
                Stopwatch _benchmarkTimer = new Stopwatch();
                _benchmarkTimer.Reset();
                _benchmarkTimer.Start();
                //BenchmarkThreadRoutineStartSettup();
                // wait a little longer then the benchmark routine if exit false throw
                //var timeoutTime = BenchmarkTimeoutInSeconds(BenchmarkTimeInSeconds);
                //var exitSucces = BenchmarkHandle.WaitForExit(timeoutTime * 1000);
                // don't use wait for it breaks everything
                BenchmarkProcessStatus = BenchmarkProcessStatus.Running;
                bool keepRunning = true;
                while (keepRunning && IsActiveProcess(BenchmarkHandle.Id))
                {
                    //string outdata = BenchmarkHandle.StandardOutput.ReadLine();
                    //BenchmarkOutputErrorDataReceivedImpl(outdata);
                    // terminate process situations
                    if (_benchmarkTimer.Elapsed.TotalSeconds >= (benchmarkTimeWait + 2) ||
                        BenchmarkSignalQuit ||
                        BenchmarkSignalFinnished ||
                        BenchmarkSignalHanged ||
                        BenchmarkSignalTimedout ||
                        BenchmarkException != null)
                    {
                        string imageName = MinerExeName.Replace(".exe", "");
                        // maybe will have to KILL process
                        KillProspectorClaymoreMinerBase(imageName);
                        if (BenchmarkSignalTimedout)
                        {
                            throw new Exception("Benchmark timedout");
                        }
                        if (BenchmarkException != null)
                        {
                            throw BenchmarkException;
                        }
                        if (BenchmarkSignalQuit)
                        {
                            throw new Exception("Termined by user request");
                        }
                        if (BenchmarkSignalFinnished)
                        {
                            break;
                        }
                        keepRunning = false;
                        break;
                    }
                    else
                    {
                        // wait a second reduce CPU load
                        Thread.Sleep(1000);
                    }
                }
            } catch (Exception ex) {
                BenchmarkThreadRoutineCatch(ex);
            } finally {
                BenchmarkAlgorithm.BenchmarkSpeed = 0;
                // find latest log file
                string latestLogFile = "";
                var    dirInfo       = new DirectoryInfo(this.WorkingDirectory);
                foreach (var file in dirInfo.GetFiles("*_log.txt"))
                {
                    latestLogFile = file.Name;
                    break;
                }
                BenchmarkHandle.WaitForExit(10000);
                // read file log
                if (File.Exists(WorkingDirectory + latestLogFile))
                {
                    var lines         = File.ReadAllLines(WorkingDirectory + latestLogFile);
                    var addBenchLines = bench_lines.Count == 0;
                    ProcessBenchLinesAlternate(lines);
                }
                BenchmarkThreadRoutineFinish();
            }
        }
Beispiel #6
0
        virtual protected bool BenchmarkParseLine(string outdata)
        {
            // parse line
            if (outdata.Contains("Benchmark: ") && outdata.Contains("/s"))
            {
                int    i         = outdata.IndexOf("Benchmark:");
                int    k         = outdata.IndexOf("/s");
                string hashspeed = outdata.Substring(i + 11, k - i - 9);
                Helpers.ConsolePrint("BENCHMARK", "Final Speed: " + hashspeed);

                // save speed
                int    b   = hashspeed.IndexOf(" ");
                double spd = Double.Parse(hashspeed.Substring(0, b), CultureInfo.InvariantCulture);
                if (hashspeed.Contains("kH/s"))
                {
                    spd *= 1000;
                }
                else if (hashspeed.Contains("MH/s"))
                {
                    spd *= 1000000;
                }
                else if (hashspeed.Contains("GH/s"))
                {
                    spd *= 1000000000;
                }
                SupportedAlgorithms[BenchmarkIndex].BenchmarkSpeed = spd;

                OnBenchmarkComplete(true, PrintSpeed(spd), BenchmarkTag);
                return(true);
            }
            else if (outdata.Contains("Average hashrate:") && outdata.Contains("/s"))
            {
                int i = outdata.IndexOf(": ");
                int k = outdata.IndexOf("/s");

                // save speed
                string hashSpeed = outdata.Substring(i + 2, k - i + 2);
                Helpers.ConsolePrint("BENCHMARK", "Final Speed: " + hashSpeed);

                hashSpeed = hashSpeed.Substring(0, hashSpeed.IndexOf(" "));
                double speed = Double.Parse(hashSpeed, CultureInfo.InvariantCulture);

                if (outdata.Contains("Kilohash"))
                {
                    speed *= 1000;
                }
                else if (outdata.Contains("Megahash"))
                {
                    speed *= 1000000;
                }

                SupportedAlgorithms[BenchmarkIndex].BenchmarkSpeed = speed;

                OnBenchmarkComplete(true, PrintSpeed(speed), BenchmarkTag);
                return(true);
            }
            else if (outdata.Contains("min/mean/max:"))
            {
                string[] splt    = outdata.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                int      index   = Array.IndexOf(splt, "mean");
                double   avg_spd = Convert.ToDouble(splt[index + 2]);
                Helpers.ConsolePrint("BENCHMARK", "Final Speed: " + avg_spd + "H/s");

                SupportedAlgorithms[BenchmarkIndex].BenchmarkSpeed = avg_spd;

                OnBenchmarkComplete(true, PrintSpeed(avg_spd), BenchmarkTag);
                return(true);
            }

            return(false);
        }
Beispiel #7
0
        public APIData GetSummary()
        {
            string  resp;
            string  aname = null;
            APIData ad    = new APIData();

            if (AlgoNameIs("daggerhashimoto"))
            {
                try
                {
                    FillAlgorithm("daggerhashimoto", ref ad);
                    if (ER.GetIsRunning() && ER.GetDAGprogress() != 100 && ER.GetSpeed() < 1)
                    {
                        ad.AlgorithmName = "Creating DAG " + ER.GetDAGprogress().ToString() + "%";
                        aname            = "Creating DAG File";
                        ad.Speed         = 0;
                    }
                    else
                    {
                        double time = 10;
                        if (ER.GetIsRunning())
                        {
                            time = 30;
                        }
                        if ((DateTime.Now.Subtract(ER.GetLastActiveTime())).TotalSeconds > time)
                        {
                            Helpers.ConsolePrint(MinerDeviceName, "ethminer is not running.. restarting..");
                            Restart();
                            return(null);
                        }

                        ad.Speed = ER.GetSpeed() * 1000 * 1000;
                    }
                }
                catch (Exception e)
                {
                    Helpers.ConsolePrint(MinerDeviceName, "GetSummary: " + e.Message);
                    return(null);
                }
            }
            else
            {
                resp = GetAPIData(APIPort, "summary");
                if (resp == null)
                {
                    return(null);
                }

                try
                {
                    string[] resps;

                    if (!MinerDeviceName.Equals("AMD_OpenCL"))
                    {
                        resps = resp.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < resps.Length; i++)
                        {
                            string[] optval = resps[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                            if (optval.Length != 2)
                            {
                                continue;
                            }
                            if (optval[0] == "ALGO")
                            {
                                aname = optval[1];
                            }
                            else if (optval[0] == "KHS")
                            {
                                ad.Speed = double.Parse(optval[1], CultureInfo.InvariantCulture) * 1000; // HPS
                            }
                        }
                    }
                    else
                    {
                        // Checks if all the GPUs are Alive first
                        string resp2 = GetAPIData(APIPort, "devs");
                        if (resp2 == null)
                        {
                            return(null);
                        }

                        string[] checkGPUStatus = resp2.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        for (int i = 1; i < checkGPUStatus.Length - 1; i++)
                        {
                            if (!checkGPUStatus[i].Contains("Status=Alive"))
                            {
                                Helpers.ConsolePrint(MinerDeviceName, "GPU " + i + ": Sick/Dead/NoStart/Initialising/Disabled/Rejecting/Unknown");
                                return(null);
                            }
                        }

                        resps = resp.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        if (resps[1].Contains("SUMMARY"))
                        {
                            string[] data = resps[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            // Get miner's current total speed
                            string[] speed = data[4].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                            // Get miner's current total MH
                            double total_mh = Double.Parse(data[18].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1], new CultureInfo("en-US"));

                            ad.Speed = Double.Parse(speed[1]) * 1000;

                            aname = SupportedAlgorithms[CurrentAlgo].MinerName;

                            if (total_mh <= PreviousTotalMH)
                            {
                                Helpers.ConsolePrint(MinerDeviceName, "SGMiner might be stuck as no new hashes are being produced");
                                Helpers.ConsolePrint(MinerDeviceName, "Prev Total MH: " + PreviousTotalMH + " .. Current Total MH: " + total_mh);
                                return(null);
                            }

                            PreviousTotalMH = total_mh;
                        }
                        else
                        {
                            ad.Speed = 0;
                        }
                    }
                }
                catch
                {
                    return(null);
                }

                FillAlgorithm(aname, ref ad);
            }

            return(ad);
        }
Beispiel #8
0
        protected void QueryCDevs()
        {
            try
            {
                Process P = new Process();
                P.StartInfo.FileName              = Path;
                P.StartInfo.UseShellExecute       = false;
                P.StartInfo.RedirectStandardError = true;
                P.StartInfo.CreateNoWindow        = true;

                string outdata;

                for (int i = 0; i < 4; i++)
                {
                    P.StartInfo.Arguments = "--gpu-platform " + i + " --ndevs";
                    P.Start();

                    do
                    {
                        outdata = P.StandardError.ReadLine();
                        if (outdata != null)
                        {
                            if (outdata.Contains("CL Platform name") && outdata.Contains("AMD"))
                            {
                                GPUPlatformNumber = i;
                                i = 20;
                            }
                            else if (outdata.Contains("Specified platform that does not exist"))
                            {
                                GPUPlatformNumber = -1;
                                i = 20;
                            }
                        }
                    } while (outdata != null);

                    P.WaitForExit();
                }

                if (GPUPlatformNumber == -1)
                {
                    Helpers.ConsolePrint(MinerDeviceName, "No AMD GPUs found.");
                    return;
                }

                P.StartInfo.Arguments = "--gpu-platform " + GPUPlatformNumber + " --ndevs";
                P.Start();

                do
                {
                    outdata = P.StandardError.ReadLine();
                    if (outdata != null)
                    {
                        AddPotentialCDev(outdata);
                    }
                } while (outdata != null);

                P.WaitForExit();

                PlatformDevices = tmpPlatformDevices;
            }
            catch (Exception e)
            {
                Helpers.ConsolePrint(MinerDeviceName, "Exception: " + e.ToString());

                MinerFileNotFoundDialog WarningDialog = new MinerFileNotFoundDialog(MinerDeviceName, Path);
                WarningDialog.ShowDialog();

                if (WarningDialog.DisableDetection)
                {
                    Config.ConfigData.DisableDetectionAMD = true;
                }

                WarningDialog = null;

                return;
            }

            // Check for optimized version
            for (int i = 0; i < GPUCodeName.Count; i++)
            {
                Helpers.ConsolePrint(MinerDeviceName, "List: " + GPUCodeName[i]);
                if (!(GPUCodeName[i].Equals("Bonaire") || GPUCodeName[i].Equals("Fiji") || GPUCodeName[i].Equals("Hawaii") ||
                      GPUCodeName[i].Equals("Pitcairn") || GPUCodeName[i].Equals("Tahiti") || GPUCodeName[i].Equals("Tonga")))
                {
                    Helpers.ConsolePrint(MinerDeviceName, "GPU (" + GPUCodeName[i] + ") is not optimized. Switching to general sgminer.");
                    EnableOptimizedVersion = false;
                }
                else
                {
                    SupportedAlgorithms[GetAlgoIndex("x11")].ExtraLaunchParameters       = DefaultParam + "--nfactor 10 --xintensity 1024 --thread-concurrency 0 --worksize 64 --gpu-threads 1";
                    SupportedAlgorithms[GetAlgoIndex("qubit")].ExtraLaunchParameters     = DefaultParam + "--nfactor 10 --xintensity 1024 --thread-concurrency 0 --worksize 64 --gpu-threads 1";
                    SupportedAlgorithms[GetAlgoIndex("quark")].ExtraLaunchParameters     = DefaultParam + "--nfactor 10 --xintensity 1024 --thread-concurrency 0 --worksize 64 --gpu-threads 1";
                    SupportedAlgorithms[GetAlgoIndex("lyra2rev2")].ExtraLaunchParameters = DefaultParam + "--nfactor 10 --xintensity 512  --thread-concurrency 0 --worksize 64 --gpu-threads 1";
                }

                if (!GPUCodeName[i].Equals("Tahiti"))
                {
                    SupportedAlgorithms[GetAlgoIndex("neoscrypt")].ExtraLaunchParameters = DefaultParam + "--nfactor 10 --xintensity    2 --thread-concurrency 8192 --worksize  64 --gpu-threads 2";
                    Helpers.ConsolePrint(MinerDeviceName, "The GPU detected (" + GPUCodeName[i] + ") is not Tahiti. Changing default gpu-threads to 2.");
                }
            }

            // check the driver version
            bool ShowWarningDialog         = false;
            ManagementObjectCollection moc = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController").Get();

            foreach (var manObj in moc)
            {
                Helpers.ConsolePrint(MinerDeviceName, "GPU Name (Driver Ver): " + manObj["Name"] + " (" + manObj["DriverVersion"] + ")");

                if ((manObj["Name"].ToString().Contains("AMD") || manObj["Name"].ToString().Contains("Radeon")) && ShowWarningDialog == false)
                {
                    if (GPUCodeName.Count > 0 && CDevs.Count < GPUCodeName.Count)
                    {
                        Helpers.ConsolePrint(MinerDeviceName, "Adding missed GPUs: " + manObj["name"].ToString());
                        CDevs.Add(new ComputeDevice(CDevs.Count, MinerDeviceName, manObj["Name"].ToString()));
                    }

                    Version AMDDriverVersion = new Version(manObj["DriverVersion"].ToString());

                    if (AMDDriverVersion.Major < 15)
                    {
                        ShowWarningDialog      = true;
                        EnableOptimizedVersion = false;
                        Helpers.ConsolePrint(MinerDeviceName, "WARNING!!! Old AMD GPU driver detected! All optimized versions disabled, mining " +
                                             "speed will not be optimal. Consider upgrading AMD GPU driver. Recommended AMD GPU driver version is 15.7.1.");
                    }
                    else if (AMDDriverVersion.Major == 16 && AMDDriverVersion.Minor >= 150)
                    {
                        string src = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\" +
                                     Path.Split('\\')[0] + "\\" + Path.Split('\\')[1] + "\\kernel";

                        foreach (var file in Directory.GetFiles(src))
                        {
                            string dest = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Temp\\" + System.IO.Path.GetFileName(file);
                            if (!File.Exists(dest))
                            {
                                File.Copy(file, dest, false);
                            }
                        }
                    }
                }
            }

            if (EnableOptimizedVersion == false)
            {
                SupportedAlgorithms[GetAlgoIndex("x11")].ExtraLaunchParameters       = DefaultParam + "--nfactor 10 --xintensity 64 --thread-concurrency 0 --worksize 64 --gpu-threads 2";
                SupportedAlgorithms[GetAlgoIndex("qubit")].ExtraLaunchParameters     = DefaultParam + "--nfactor 10 --xintensity 64 --thread-concurrency 0 --worksize 128 --gpu-threads 4";
                SupportedAlgorithms[GetAlgoIndex("quark")].ExtraLaunchParameters     = DefaultParam + "--nfactor 10 --xintensity 64 --thread-concurrency 0 --worksize 256 --gpu-threads 1";
                SupportedAlgorithms[GetAlgoIndex("lyra2rev2")].ExtraLaunchParameters = DefaultParam + "--nfactor 10 --xintensity 64 --thread-concurrency 0 --worksize 64 --gpu-threads 2";
            }

            if (ShowWarningDialog == true && Config.ConfigData.ShowDriverVersionWarning == true)
            {
                Form WarningDialog = new DriverVersionConfirmationDialog();
                WarningDialog.ShowDialog();
                WarningDialog = null;
            }

            // Check for ethereum mining
            EtherDevices = new int[CDevs.Count];

            try
            {
                Process P = new Process();
                P.StartInfo.FileName              = Ethereum.EtherMinerPath;
                P.StartInfo.UseShellExecute       = false;
                P.StartInfo.RedirectStandardError = true;
                P.StartInfo.CreateNoWindow        = true;

                string outdata;

                Helpers.ConsolePrint(MinerDeviceName, "Adding Ethereum..");
                P.StartInfo.Arguments = "--list-devices --opencl";
                P.Start();

                int i = 0;
                do
                {
                    outdata = P.StandardError.ReadLine();
                    if (outdata != null)
                    {
                        if (outdata.Contains("Intel") || outdata.Contains("GeForce"))
                        {
                            // skips to the next GPU
                            P.StandardError.ReadLine();
                            P.StandardError.ReadLine();
                            P.StandardError.ReadLine();
                            P.StandardError.ReadLine();
                            continue;
                        }

                        if (outdata.Contains("CL_DEVICE_GLOBAL_MEM_SIZE"))
                        {
                            long memsize = Convert.ToInt64(outdata.Split(':')[1]);
                            if (memsize >= 2147483648)
                            {
                                Helpers.ConsolePrint(MinerDeviceName, "Ethereum GPU MemSize: " + memsize + " (GOOD!)");
                                EtherDevices[i] = i;
                                i++;
                            }
                            else
                            {
                                Helpers.ConsolePrint(MinerDeviceName, "Ethereum GPU MemSize: " + memsize + " (NOT GOOD!)");
                                EtherDevices[i] = -1;
                                i++;
                            }
                        }
                    }
                } while (outdata != null);

                P.WaitForExit();
            }
            catch (Exception e)
            {
                Helpers.ConsolePrint(MinerDeviceName, "Exception: " + e.ToString());
            }
        }
Beispiel #9
0
        static void Main(string[] argv)
        {
            // Set working directory to exe
            var pathSet = false;
            var path    = Path.GetDirectoryName(Application.ExecutablePath);

            if (path != null)
            {
                Environment.CurrentDirectory = path;
                pathSet = true;
            }

            // Add common folder to path for launched processes
            var pathVar = Environment.GetEnvironmentVariable("PATH");

            pathVar += ";" + Path.Combine(Environment.CurrentDirectory, "common");
            Environment.SetEnvironmentVariable("PATH", pathVar);


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            //Console.OutputEncoding = System.Text.Encoding.Unicode;
            // #0 set this first so data parsing will work correctly
            Globals.JsonSettings = new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                Culture = CultureInfo.InvariantCulture
            };
            // #1 first initialize config
            ConfigManager.InitializeConfig();

            // #2 check if multiple instances are allowed
            if (ConfigManager.GeneralConfig.AllowMultipleInstances == false)
            {
                try
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            // already running instance, return from Main
                            return;
                        }
                    }
                }
                catch { }
            }

            // start program
            if (ConfigManager.GeneralConfig.LogToFile)
            {
                Logger.ConfigureWithFile();
            }

            if (ConfigManager.GeneralConfig.DebugConsole)
            {
                PInvokeHelpers.AllocConsole();
            }

            // init active display currency after config load
            ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

            Helpers.ConsolePrint("NICEHASH", "Starting up NiceHashMiner v" + Application.ProductVersion);

            if (!pathSet)
            {
                Helpers.ConsolePrint("NICEHASH", "Path not set to executable");
            }

            // check TOS
            if (ConfigManager.GeneralConfig.agreedWithTOS != Globals.CurrentTosVer)
            {
                Helpers.ConsolePrint("NICEHASH", $"TOS differs! agreed: {ConfigManager.GeneralConfig.agreedWithTOS} != Current {Globals.CurrentTosVer}. Showing TOS Form.");
                Application.Run(new FormEula());
                // check TOS after
                if (ConfigManager.GeneralConfig.agreedWithTOS != Globals.CurrentTosVer)
                {
                    Helpers.ConsolePrint("NICEHASH", $"TOS differs AFTER TOS confirmation FORM");
                    // TOS not confirmed return from Main
                    return;
                }
            }
            // if config created show language select
            if (string.IsNullOrEmpty(ConfigManager.GeneralConfig.Language))
            {
                if (Translations.GetAvailableLanguagesNames().Count > 1)
                {
                    Application.Run(new Form_ChooseLanguage());
                }
                else
                {
                    ConfigManager.GeneralConfig.Language = "en";
                    ConfigManager.GeneralConfigFileCommit();
                }
            }
            Translations.SetLanguage(ConfigManager.GeneralConfig.Language);

            // check WMI
            if (Helpers.IsWmiEnabled())
            {
                // if no BTC address show login/register form
                if (ConfigManager.GeneralConfig.BitcoinAddress.Trim() == "")
                {
                    Application.Run(new EnterBTCDialogSwitch());
                }
                // finally run
                Application.Run(new Form_Main());
            }
            else
            {
                MessageBox.Show(Translations.Tr("NiceHash Miner Legacy cannot run needed components. It seems that your system has Windows Management Instrumentation service Disabled. In order for NiceHash Miner Legacy to work properly Windows Management Instrumentation service needs to be Enabled. This service is needed to detect RAM usage and Avaliable Video controler information. Enable Windows Management Instrumentation service manually and start NiceHash Miner Legacy."),
                                Translations.Tr("Windows Management Instrumentation Error"),
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #10
0
        protected override string BenchmarkCreateCommandLine(int index, int time)
        {
            Algorithm Algo = GetMinerAlgorithm(SupportedAlgorithms[index].NiceHashID);

            if (Algo == null)
            {
                Helpers.ConsolePrint(MinerDeviceName, "GetMinerAlgorithm(" + index + "): Algo equals to null");
                return("");
            }

            string CommandLine;

            if (Algo.NiceHashName.Equals("daggerhashimoto"))
            {
                CommandLine = " --opencl --opencl-platform " + GPUPlatformNumber +
                              " " + ExtraLaunchParameters +
                              " " + Algo.ExtraLaunchParameters +
                              " --benchmark-warmup 40 --benchmark-trial 20" +
                              " --opencl-devices ";

                int dagdev = -1;
                for (int i = 0; i < CDevs.Count; i++)
                {
                    if (EtherDevices[i] != -1 && CDevs[i].Enabled && !Algo.DisabledDevice[i])
                    {
                        CommandLine += i + " ";
                        if (i == DaggerHashimotoGenerateDevice)
                        {
                            dagdev = DaggerHashimotoGenerateDevice;
                        }
                        else if (dagdev == -1)
                        {
                            dagdev = i;
                        }
                    }
                }

                CommandLine += " --dag-load-mode single " + dagdev.ToString();

                Ethereum.GetCurrentBlock(MinerDeviceName);
                CommandLine += " --benchmark " + Ethereum.CurrentBlockNum;
            }
            else
            {
                Path = "cmd";
                string DirName = GetMinerDirectory(Algo.NiceHashName);

                string url = "stratum+tcp://" + Globals.NiceHashData[SupportedAlgorithms[index].NiceHashID].name + "." +
                             Globals.MiningLocation[Config.ConfigData.ServiceLocation] + ".nicehash.com:" +
                             Globals.NiceHashData[SupportedAlgorithms[index].NiceHashID].port;

                string username = Config.ConfigData.BitcoinAddress.Trim();
                if (Config.ConfigData.WorkerName.Length > 0)
                {
                    username += "." + Config.ConfigData.WorkerName.Trim();
                }

                CommandLine = " /C \"cd /d " + DirName + " && sgminer.exe " +
                              " --gpu-platform " + GPUPlatformNumber +
                              " -k " + SupportedAlgorithms[index].MinerName +
                              " --url=" + url +
                              " --userpass="******":" + GetPassword(Algo) +
                              " --sched-stop " + DateTime.Now.AddMinutes(time).ToString("HH:mm") +
                              " -T --log 10 --log-file dump.txt" +
                              " " + ExtraLaunchParameters +
                              " " + SupportedAlgorithms[index].ExtraLaunchParameters +
                              " --device ";

                for (int i = 0; i < CDevs.Count; i++)
                {
                    if (CDevs[i].Enabled && !Algo.DisabledDevice[i])
                    {
                        CommandLine += CDevs[i].ID.ToString() + ",";
                    }
                }

                CommandLine = CommandLine.Remove(CommandLine.Length - 1);
                if (Config.ConfigData.DisableAMDTempControl == false)
                {
                    CommandLine += TemperatureParam;
                }
                CommandLine += " && del dump.txt\"";
            }

            return(CommandLine);
        }
Beispiel #11
0
        public override void Start(int nhalgo, string url, string username)
        {
            //if (ProcessHandle != null) return; // ignore, already running

            Algorithm Algo = GetMinerAlgorithm(nhalgo);

            if (Algo == null)
            {
                Helpers.ConsolePrint(MinerDeviceName, "GetMinerAlgorithm(" + nhalgo + "): Algo equals to null");
                return;
            }

            if (Algo.NiceHashName.Equals("daggerhashimoto"))
            {
                WorkingDirectory = "";
                LastCommandLine  = " --opencl --opencl-platform " + GPUPlatformNumber +
                                   " " + ExtraLaunchParameters +
                                   " " + Algo.ExtraLaunchParameters +
                                   " -S " + url.Substring(14) +
                                   " -O " + username + ":" + GetPassword(Algo) +
                                   " --api-port " + Config.ConfigData.ethminerAPIPortAMD.ToString() +
                                   " --opencl-devices ";

                int dagdev = -1;
                for (int i = 0; i < CDevs.Count; i++)
                {
                    if (EtherDevices[i] != -1 && CDevs[i].Enabled && !Algo.DisabledDevice[i])
                    {
                        LastCommandLine += i.ToString() + " ";
                        if (i == DaggerHashimotoGenerateDevice)
                        {
                            dagdev = DaggerHashimotoGenerateDevice;
                        }
                        else if (dagdev == -1)
                        {
                            dagdev = i;
                        }
                    }
                }

                LastCommandLine += " --dag-load-mode singlekeep " + dagdev.ToString();
            }
            else
            {
                StartingUpDelay = true;

                WorkingDirectory = GetMinerDirectory(Algo.NiceHashName);
                Path             = WorkingDirectory + "sgminer.exe";

                LastCommandLine = " --gpu-platform " + GPUPlatformNumber +
                                  " -k " + Algo.MinerName +
                                  " --url=" + url +
                                  " --userpass="******":" + GetPassword(Algo) +
                                  " --api-listen" +
                                  " --api-port=" + APIPort.ToString() +
                                  " " + ExtraLaunchParameters +
                                  " " + Algo.ExtraLaunchParameters +
                                  " --device ";

                for (int i = 0; i < CDevs.Count; i++)
                {
                    if (CDevs[i].Enabled && !Algo.DisabledDevice[i])
                    {
                        LastCommandLine += CDevs[i].ID.ToString() + ",";
                    }
                }

                if (LastCommandLine.EndsWith(","))
                {
                    LastCommandLine = LastCommandLine.Remove(LastCommandLine.Length - 1);
                }
                else
                {
                    LastCommandLine = "";
                    return; // no GPUs to start mining on
                }

                if (Config.ConfigData.DisableAMDTempControl == false)
                {
                    LastCommandLine += TemperatureParam;
                }
            }

            ProcessHandle = _Start();
        }
        static void Main(string[] argv)
        {
            // Set working directory to exe
            Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            //Console.OutputEncoding = System.Text.Encoding.Unicode;
            // #0 set this first so data parsing will work correctly
            Globals.JsonSettings = new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                Culture = CultureInfo.InvariantCulture
            };

            // #1 first initialize config
            ConfigManager.InitializeConfig();

            // #2 check if multiple instances are allowed
            var startProgram = true;

            if (ConfigManager.GeneralConfig.AllowMultipleInstances == false)
            {
                try
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            startProgram = false;
                        }
                    }
                }
                catch { }
            }

            if (startProgram)
            {
                if (ConfigManager.GeneralConfig.LogToFile)
                {
                    Logger.ConfigureWithFile();
                }

                if (ConfigManager.GeneralConfig.DebugConsole)
                {
                    PInvokeHelpers.AllocConsole();
                }

                // init active display currency after config load
                ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

                // #2 then parse args
                var commandLineArgs = new CommandLineParser(argv);

                Helpers.ConsolePrint("NICEHASH", "Starting up NiceHashMiner v" + Application.ProductVersion);
                var tosChecked = ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer;
                if (!tosChecked || !ConfigManager.GeneralConfigIsFileExist() && !commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH",
                                         "No config file found. Running NiceHash Miner Legacy for the first time. Choosing a default language.");
                    Application.Run(new Form_ChooseLanguage());
                }

                // Init languages
                International.Initialize(ConfigManager.GeneralConfig.Language);

                if (commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH", "Language is overwritten by command line parameter (-lang).");
                    International.Initialize(commandLineArgs.LangValue);
                    ConfigManager.GeneralConfig.Language = commandLineArgs.LangValue;
                }

                // check WMI
                if (Helpers.IsWmiEnabled())
                {
                    if (ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer)
                    {
                        Application.Run(new Form_Main());
                    }
                }
                else
                {
                    MessageBox.Show(International.GetText("Program_WMI_Error_Text"),
                                    International.GetText("Program_WMI_Error_Title"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #13
0
        private void InitiateBenchmark()
        {
            if (listView1.Items.Count > index)
            {
                string       err;
                ListViewItem lvi = listView1.Items[index];
                index++;

                if (!lvi.Checked)
                {
                    InitiateBenchmark();
                    return;
                }

                Miner m = lvi.Tag as Miner;
                int   i = (int)lvi.SubItems[2].Tag;
                lvi.SubItems[3].Text  = "Please wait...";
                inBenchmark           = true;
                CurrentlyBenchmarking = m;

                if (m is cpuminer)
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsCPU[TimeIndex];
                    lvi.SubItems[3].Text = "Please wait about " + Time + " seconds...";
                }
                else if (m is ccminer)
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsNVIDIA[TimeIndex];

                    if (lvi.SubItems[2].Text.Equals("daggerhashimoto"))
                    {
                        lvi.SubItems[3].Text = "Creating DAG file (10-20 minutes)..";
                        if (Ethereum.CreateDAGFile(true, m.MinerDeviceName, out err) == false)
                        {
                            lvi.SubItems[3].Text = err;
                            InitiateBenchmark();
                            return;
                        }
                        lvi.SubItems[3].Text = "Benchmarking (2-4 minutes)...";
                    }
                    else
                    {
                        lvi.SubItems[3].Text = "Please wait about " + Time + " seconds...";
                    }
                }
                else
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsAMD[TimeIndex] / 60;

                    // add an aditional minute if second is not 0
                    if (DateTime.Now.Second != 0)
                    {
                        Time += 1;
                    }

                    if (lvi.SubItems[2].Text.Equals("daggerhashimoto"))
                    {
                        lvi.SubItems[3].Text = "Creating DAG file (10-20 minutes)..";
                        if (Ethereum.CreateDAGFile(true, m.MinerDeviceName, out err) == false)
                        {
                            lvi.SubItems[3].Text = err;
                            InitiateBenchmark();
                            return;
                        }
                        lvi.SubItems[3].Text = "Benchmarking (2-4 minutes)...";
                    }
                    else
                    {
                        lvi.SubItems[3].Text = "Please wait about " + Time + " minutes...";
                    }
                }

                m.BenchmarkStart(i, Time, BenchmarkCompleted, lvi);
            }
            else
            {
                // average all cpu benchmarks
                if (Form1.Miners[0] is cpuminer)
                {
                    Helpers.ConsolePrint("BENCHMARK", "Calculating average CPU speeds:");

                    double[] Speeds = new double[Form1.Miners[0].SupportedAlgorithms.Length];
                    int[]    MTaken = new int[Form1.Miners[0].SupportedAlgorithms.Length];

                    foreach (ListViewItem lvi in listView1.Items)
                    {
                        if (lvi.Tag is cpuminer)
                        {
                            Miner m = lvi.Tag as Miner;
                            int   i = (int)lvi.SubItems[2].Tag;
                            if (m.SupportedAlgorithms[i].BenchmarkSpeed > 0)
                            {
                                Speeds[i] += m.SupportedAlgorithms[i].BenchmarkSpeed;
                                MTaken[i]++;
                            }
                        }
                    }

                    for (int i = 0; i < Speeds.Length; i++)
                    {
                        if (MTaken[i] > 0)
                        {
                            Speeds[i] /= MTaken[i];
                        }
                        Helpers.ConsolePrint("BENCHMARK", Form1.Miners[0].SupportedAlgorithms[i].NiceHashName + " average speed: " + Form1.Miners[0].PrintSpeed(Speeds[i]));

                        foreach (Miner m in Form1.Miners)
                        {
                            if (m is cpuminer)
                            {
                                m.SupportedAlgorithms[i].BenchmarkSpeed = Speeds[i];
                            }
                        }
                    }
                }

                foreach (ListViewItem lvi in listView1.Items)
                {
                    Miner m = lvi.Tag as Miner;
                    int   i = (int)lvi.SubItems[2].Tag;
                    lvi.SubItems[3].Text = m.PrintSpeed(m.SupportedAlgorithms[i].BenchmarkSpeed);
                }

                Config.RebuildGroups();

                button1.Enabled = true;
                button2.Enabled = false;
                button3.Enabled = true;
                button4.Enabled = true;
            }
        }
Beispiel #14
0
 private void SmaCallback(object sender, EventArgs e)
 {
     Helpers.ConsolePrint("NICEHASH", "SMA Update");
     //_isSmaUpdated = true;
 }
Beispiel #15
0
        virtual protected NiceHashProcess _Start()
        {
            // check if dagger already running
            if (AlgoNameIs("daggerhashimoto") && ethminerProcess != null)
            {
                Helpers.ConsolePrint(MinerDeviceName, "Resuming ethminer..");
                ethminerLink.StartMining();
                IsRunning = true;
                return(null);
            }

            PreviousTotalMH = 0.0;
            if (LastCommandLine.Length == 0 || EnabledDeviceCount() == 0)
            {
                return(null);
            }

            NiceHashProcess P = new NiceHashProcess();

            if (WorkingDirectory.Length > 1)
            {
                P.StartInfo.WorkingDirectory = WorkingDirectory;
            }

            NumRetries = Config.ConfigData.MinerAPIGraceSeconds / Config.ConfigData.MinerAPIQueryInterval;
            if (this is sgminer && !AlgoNameIs("daggerhashimoto"))
            {
                NumRetries = (Config.ConfigData.MinerAPIGraceSeconds + Config.ConfigData.MinerAPIGraceSecondsAMD) / Config.ConfigData.MinerAPIQueryInterval;
            }

            if (AlgoNameIs("daggerhashimoto"))
            {
                ethminerLink         = new ethminerAPI((this is sgminer) ? Config.ConfigData.ethminerAPIPortAMD : Config.ConfigData.ethminerAPIPortNvidia);
                P.StartInfo.FileName = Ethereum.EtherMinerPath;
                P.ExitEvent          = ethMiner_Exited;
            }
            else
            {
                P.StartInfo.FileName = Path;
                P.ExitEvent          = Miner_Exited;
            }

            P.StartInfo.Arguments       = LastCommandLine;
            P.StartInfo.CreateNoWindow  = Config.ConfigData.HideMiningWindows;
            P.StartInfo.UseShellExecute = false;

            Helpers.ConsolePrint(MinerDeviceName, "Starting miner (" + P.StartInfo.FileName + "): " + LastCommandLine);

            try
            {
                if (P.Start())
                {
                    IsRunning = true;

                    if (AlgoNameIs("daggerhashimoto"))
                    {
                        ethminerProcess = P;
                        return(null);
                    }
                    return(P);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Helpers.ConsolePrint(MinerDeviceName, "_Start: " + ex.Message);
                return(null);
            }
        }
Beispiel #16
0
        virtual protected void BenchmarkThreadRoutine(object CommandLine)
        {
            Thread.Sleep(Config.ConfigData.MinerRestartDelayMS);

            BenchmarkSignalQuit = false;

            Process BenchmarkHandle = null;

            try
            {
                BenchmarkHandle = BenchmarkStartProcess((string)CommandLine);

                while (true)
                {
                    string outdata = BenchmarkGetConsoleOutputLine(BenchmarkHandle);
                    if (outdata != null)
                    {
                        //Helpers.ConsolePrint(outdata);
                        if (outdata.Contains("Cuda error"))
                        {
                            throw new Exception("CUDA error");
                        }
                        if (outdata.Contains("is not supported"))
                        {
                            throw new Exception("N/A");
                        }
                        if (outdata.Contains("illegal memory access"))
                        {
                            throw new Exception("CUDA error");
                        }
                        if (BenchmarkParseLine(outdata))
                        {
                            break;
                        }
                    }
                    if (BenchmarkSignalQuit)
                    {
                        throw new Exception("Termined by user request");
                    }
                }
            }
            catch (Exception ex)
            {
                SupportedAlgorithms[BenchmarkIndex].BenchmarkSpeed = 0;

                Helpers.ConsolePrint(ex.Message);

                try { if (BenchmarkHandle != null)
                      {
                          BenchmarkHandle.Kill();
                      }
                }
                catch { }

                OnBenchmarkComplete(false, "Terminated", BenchmarkTag);
            }

            if (BenchmarkHandle != null)
            {
                BenchmarkHandle.Close();
            }
        }
Beispiel #17
0
        public APIData GetSummary()
        {
            string  resp;
            string  aname = null;
            APIData ad    = new APIData();

            if (AlgoNameIs("daggerhashimoto"))
            {
                FillAlgorithm("daggerhashimoto", ref ad);

                bool ismining;
                if (!ethminerLink.GetSpeed(out ismining, out ad.Speed))
                {
                    if (NumRetries > 0)
                    {
                        NumRetries--;
                        ad.Speed = 0;
                        return(ad);
                    }

                    Helpers.ConsolePrint(MinerDeviceName, "ethminer is not running.. restarting..");
                    Stop(false);
                    _Start();
                    ad.Speed = 0;
                    return(ad);
                }
                else if (!ismining)
                {
                    // resend start mining command
                    ethminerLink.StartMining();
                }
                ad.Speed *= 1000 * 1000;
            }
            else
            {
                resp = GetAPIData(APIPort, "summary");
                if (resp == null)
                {
                    return(null);
                }

                try
                {
                    string[] resps;

                    if (!MinerDeviceName.Equals("AMD_OpenCL"))
                    {
                        resps = resp.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < resps.Length; i++)
                        {
                            string[] optval = resps[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                            if (optval.Length != 2)
                            {
                                continue;
                            }
                            if (optval[0] == "ALGO")
                            {
                                aname = optval[1];
                            }
                            else if (optval[0] == "KHS")
                            {
                                ad.Speed = double.Parse(optval[1], CultureInfo.InvariantCulture) * 1000; // HPS
                            }
                        }
                    }
                    else
                    {
                        // Checks if all the GPUs are Alive first
                        string resp2 = GetAPIData(APIPort, "devs");
                        if (resp2 == null)
                        {
                            return(null);
                        }

                        string[] checkGPUStatus = resp2.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        for (int i = 1; i < checkGPUStatus.Length - 1; i++)
                        {
                            if (!checkGPUStatus[i].Contains("Status=Alive"))
                            {
                                Helpers.ConsolePrint(MinerDeviceName, "GPU " + i + ": Sick/Dead/NoStart/Initialising/Disabled/Rejecting/Unknown");
                                return(null);
                            }
                        }

                        resps = resp.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        if (resps[1].Contains("SUMMARY"))
                        {
                            string[] data = resps[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            // Get miner's current total speed
                            string[] speed = data[4].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                            // Get miner's current total MH
                            double total_mh = Double.Parse(data[18].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1], new CultureInfo("en-US"));

                            ad.Speed = Double.Parse(speed[1]) * 1000;

                            aname = SupportedAlgorithms[CurrentAlgo].MinerName;

                            if (total_mh <= PreviousTotalMH)
                            {
                                Helpers.ConsolePrint(MinerDeviceName, "SGMiner might be stuck as no new hashes are being produced");
                                Helpers.ConsolePrint(MinerDeviceName, "Prev Total MH: " + PreviousTotalMH + " .. Current Total MH: " + total_mh);
                                return(null);
                            }

                            PreviousTotalMH = total_mh;
                        }
                        else
                        {
                            ad.Speed = 0;
                        }
                    }
                }
                catch
                {
                    return(null);
                }

                FillAlgorithm(aname, ref ad);
            }

            return(ad);
        }
Beispiel #18
0
        public static bool CreateDAGFile(bool HideWindow, string worker, out string err)
        {
            err = null;

            try
            {
                if (!GetCurrentBlock(worker))
                {
                    throw new Exception("GetCurrentBlock returns null..");
                }

                // Check if dag-dir exist to avoid ethminer from crashing
                Helpers.ConsolePrint(worker, "Creating DAG directory for " + worker + "..");
                if (!CreateDAGDirectory(worker))
                {
                    throw new Exception("[" + worker + "] Cannot create directory for DAG files.");
                }

                if (worker.Equals("NVIDIA5.x"))
                {
                    CopyDAGFiles("NVIDIA3.x", worker);
                    CopyDAGFiles("AMD_OpenCL", worker);
                }
                else if (worker.Equals("NVIDIA3.x"))
                {
                    CopyDAGFiles("NVIDIA5.x", worker);
                    CopyDAGFiles("AMD_OpenCL", worker);
                }
                else if (worker.Equals("AMD_OpenCL"))
                {
                    CopyDAGFiles("NVIDIA5.x", worker);
                    CopyDAGFiles("NVIDIA3.x", worker);
                }

                Helpers.ConsolePrint(worker, "Creating DAG file for " + worker + "..");

                Process P = new Process();
                P.StartInfo.FileName  = EtherMinerPath;
                P.StartInfo.Arguments = " --dag-dir " + Config.ConfigData.DAGDirectory + "\\" + worker + " --create-dag " + CurrentBlockNum;
                Helpers.ConsolePrint(worker, "CreateDAGFile Arguments: " + P.StartInfo.Arguments);
                P.StartInfo.CreateNoWindow = HideWindow;
                //P.StartInfo.UseShellExecute = !HideWindow;
                P.StartInfo.UseShellExecute = false;

                Form5 f = new Form5(worker, P);
                f.ShowDialog();

                if (f.Success)
                {
                    return(true);
                }
                else
                {
                    throw new Exception(f.Error);
                }
                //P.Start();

                //P.WaitForExit();

                //P.Close();
                //P = null;
            }
            catch (Exception e)
            {
                err = e.Message;
                Helpers.ConsolePrint(worker, "Exception: " + e.Message);
                return(false);
            }

            //return true;
        }
Beispiel #19
0
        virtual protected void BenchmarkThreadRoutine(object CommandLine)
        {
            Thread.Sleep(Config.ConfigData.MinerRestartDelayMS);

            bool      once  = true;
            Stopwatch timer = new Stopwatch();

            BenchmarkSignalQuit = false;

            Process BenchmarkHandle = null;

            try
            {
                Helpers.ConsolePrint("BENCHMARK", "Benchmark starts");
                BenchmarkHandle = BenchmarkStartProcess((string)CommandLine);

                if (AlgoNameIs("daggerhashimoto"))
                {
                    string outdata = BenchmarkHandle.StandardOutput.ReadToEnd();
                    BenchmarkParseLine(outdata);
                }
                else if (this is cpuminer && AlgoNameIs("hodl"))
                {
                    int    count = BenchmarkTime / 5;
                    double total = 0, tmp;

                    while (count > 0)
                    {
                        string outdata = BenchmarkHandle.StandardError.ReadLine();
                        if (outdata != null)
                        {
                            if (outdata.Contains("Total: "))
                            {
                                int st  = outdata.IndexOf("Total:") + 7;
                                int len = outdata.Length - 6 - st;

                                string parse = outdata.Substring(st, len).Trim();
                                Double.TryParse(parse, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp);
                                total += tmp;
                                count--;
                            }
                        }
                        if (BenchmarkSignalQuit)
                        {
                            throw new Exception("Termined by user request");
                        }
                    }

                    double spd = total / (BenchmarkTime / 5);
                    SupportedAlgorithms[BenchmarkIndex].BenchmarkSpeed = spd;
                    OnBenchmarkComplete(true, PrintSpeed(spd), BenchmarkTag);
                }
                else
                {
                    if (MinerDeviceName.Equals("AMD_OpenCL"))
                    {
                        int NHDataIndex = SupportedAlgorithms[BenchmarkIndex].NiceHashID;

                        if (Form1.NiceHashData == null)
                        {
                            Helpers.ConsolePrint("BENCHMARK", "Skipping sgminer benchmark because there is no internet " +
                                                 "connection. Sgminer needs internet connection to do benchmarking.");

                            throw new Exception("No internet connection");
                        }

                        if (Form1.NiceHashData[NHDataIndex].paying == 0)
                        {
                            Helpers.ConsolePrint("BENCHMARK", "Skipping sgminer benchmark because there is no work on Nicehash.com " +
                                                 "[algo: " + SupportedAlgorithms[BenchmarkIndex].NiceHashName + "(" + NHDataIndex + ")]");

                            throw new Exception("No work can be used for benchmarking");
                        }

                        timer.Reset();
                        timer.Start();
                    }

                    while (true)
                    {
                        if (MinerDeviceName.Equals("AMD_OpenCL"))
                        {
                            if (timer.Elapsed.Minutes >= BenchmarkTime + 1 && once == true)
                            {
                                once = false;
                                string resp = GetAPIData(APIPort, "quit").TrimEnd(new char[] { (char)0 });
                                Helpers.ConsolePrint("BENCHMARK", "SGMiner Response: " + resp);
                            }
                            if (timer.Elapsed.Minutes >= BenchmarkTime + 2)
                            {
                                timer.Stop();
                                KillSGMiner();
                                BenchmarkSignalHanged = true;
                            }
                        }

                        string outdata = BenchmarkGetConsoleOutputLine(BenchmarkHandle);
                        if (outdata != null)
                        {
                            if (outdata.Contains("Cuda error"))
                            {
                                throw new Exception("CUDA error");
                            }
                            if (outdata.Contains("is not supported"))
                            {
                                throw new Exception("N/A");
                            }
                            if (outdata.Contains("illegal memory access"))
                            {
                                throw new Exception("CUDA error");
                            }
                            if (outdata.Contains("unknown error"))
                            {
                                throw new Exception("Unknown error");
                            }
                            if (outdata.Contains("No servers could be used! Exiting."))
                            {
                                throw new Exception("No pools or work can be used for benchmarking");
                            }
                            if (BenchmarkParseLine(outdata))
                            {
                                break;
                            }
                        }
                        if (BenchmarkSignalQuit)
                        {
                            throw new Exception("Termined by user request");
                        }
                        if (BenchmarkSignalHanged)
                        {
                            throw new Exception("SGMiner is not responding");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SupportedAlgorithms[BenchmarkIndex].BenchmarkSpeed = 0;

                Helpers.ConsolePrint(MinerDeviceName, "Benchmark Exception: " + ex.Message);

                try { if (BenchmarkHandle != null)
                      {
                          BenchmarkHandle.Kill();
                      }
                }
                catch { }

                OnBenchmarkComplete(false, "Terminated", BenchmarkTag);
            }
            Helpers.ConsolePrint("BENCHMARK", "Benchmark ends");

            if (BenchmarkHandle != null)
            {
                try { BenchmarkHandle.Kill(); BenchmarkHandle.Close(); }
                catch { }
            }
        }
Beispiel #20
0
        protected void QueryCDevs()
        {
            try
            {
                Process P = new Process();
                P.StartInfo.FileName              = Path;
                P.StartInfo.UseShellExecute       = false;
                P.StartInfo.RedirectStandardError = true;
                P.StartInfo.CreateNoWindow        = true;

                string outdata;

                for (int i = 0; i < 10; i++)
                {
                    P.StartInfo.Arguments = "--gpu-platform " + i + " --ndevs";
                    P.Start();

                    do
                    {
                        outdata = P.StandardError.ReadLine();
                        if (outdata != null)
                        {
                            if (outdata.Contains("CL Platform name") && outdata.Contains("AMD"))
                            {
                                GPUPlatformNumber = i;
                                i = 20;
                            }
                            else if (outdata.Contains("Specified platform that does not exist"))
                            {
                                GPUPlatformNumber = -1;
                                i = 20;
                            }
                        }
                    } while (outdata != null);

                    P.WaitForExit();
                }

                if (GPUPlatformNumber == -1)
                {
                    Helpers.ConsolePrint(MinerDeviceName, "No AMD GPUs found.");
                    return;
                }

                P.StartInfo.Arguments = "--gpu-platform " + GPUPlatformNumber + " --ndevs";
                P.Start();

                do
                {
                    outdata = P.StandardError.ReadLine();
                    if (outdata != null)
                    {
                        AddPotentialCDev(outdata);
                    }
                } while (outdata != null);

                P.WaitForExit();

                PlatformDevices = tmpPlatformDevices;
            }
            catch (Exception e)
            {
                Helpers.ConsolePrint(MinerDeviceName, "Exception: " + e.ToString());

                MinerFileNotFoundDialog WarningDialog = new MinerFileNotFoundDialog(MinerDeviceName, Path);
                WarningDialog.ShowDialog();

                if (WarningDialog.DisableDetection)
                {
                    Config.ConfigData.DisableDetectionAMD = true;
                }

                WarningDialog = null;

                return;
            }


            // check the driver version
            bool ShowWarningDialog         = false;
            ManagementObjectCollection moc = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController").Get();

            foreach (var manObj in moc)
            {
                Helpers.ConsolePrint("DEBUG", "GPU Name (Driver Ver): " + manObj["Name"] + " (" + manObj["DriverVersion"] + ")");

                if (manObj["Name"].ToString().Contains("AMD") && ShowWarningDialog == false)
                {
                    if (PlatformDevices > 0 && CDevs.Count < PlatformDevices)
                    {
                        Helpers.ConsolePrint("DEBUG", "Adding missed GPUs: " + manObj["name"].ToString());
                        CDevs.Add(new ComputeDevice(CDevs.Count, MinerDeviceName, manObj["Name"].ToString()));
                    }

                    Version AMDDriverVersion = new Version(manObj["DriverVersion"].ToString());

                    if (AMDDriverVersion.Major < 15)
                    {
                        ShowWarningDialog      = true;
                        EnableOptimizedVersion = false;
                        Helpers.ConsolePrint(MinerDeviceName, "WARNING!!! Old AMD GPU driver detected! All optimized versions disabled, mining " +
                                             "speed will not be optimal. Consider upgrading AMD GPU driver. Recommended AMD GPU driver version is 15.7.1.");
                    }
                }
            }

            if (EnableOptimizedVersion == false)
            {
                SupportedAlgorithms[0].ExtraLaunchParameters = DefaultParam + "--nfactor 10 --xintensity 64 --thread-concurrency    0 --worksize  64 --gpu-threads 2";  // x11
                SupportedAlgorithms[6].ExtraLaunchParameters = DefaultParam + "--nfactor 10 --xintensity 64 --thread-concurrency    0 --worksize 128 --gpu-threads 4";  // qubit
                SupportedAlgorithms[7].ExtraLaunchParameters = DefaultParam + "--nfactor 10 --xintensity 64 --thread-concurrency    0 --worksize 256 --gpu-threads 1";  // quark
                SupportedAlgorithms[8].ExtraLaunchParameters = DefaultParam + "--nfactor 10 --xintensity 32 --thread-concurrency 8192 --worksize  32 --gpu-threads 4";  // lyra2rev2
            }

            if (ShowWarningDialog == true && Config.ConfigData.ShowDriverVersionWarning == true)
            {
                Form WarningDialog = new DriverVersionConfirmationDialog();
                WarningDialog.ShowDialog();
                WarningDialog = null;
            }
        }
Beispiel #21
0
        static void Main(string[] argv)
        {
            // log unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionLogger);
            Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionLogger);

            // Set working directory to exe
            var pathSet = false;
            var path    = Path.GetDirectoryName(Application.ExecutablePath);

            if (path != null)
            {
                Environment.CurrentDirectory = path;
                pathSet = true;
            }

            // Add common folder to path for launched processes
            var pathVar = Environment.GetEnvironmentVariable("PATH");

            pathVar += ";" + Path.Combine(Environment.CurrentDirectory, "common");
            Environment.SetEnvironmentVariable("PATH", pathVar);


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            //Console.OutputEncoding = System.Text.Encoding.Unicode;
            // #0 set this first so data parsing will work correctly
            Globals.JsonSettings = new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                Culture = CultureInfo.InvariantCulture
            };

            // #1 first initialize config
            ConfigManager.InitializeConfig();

            // #2 check if multiple instances are allowed
            var startProgram = true;

            if (ConfigManager.GeneralConfig.AllowMultipleInstances == false)
            {
                try
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            startProgram = false;
                        }
                    }
                }
                catch { }
            }

            if (startProgram)
            {
                if (ConfigManager.GeneralConfig.LogToFile)
                {
                    Logger.ConfigureWithFile();
                }

                if (ConfigManager.GeneralConfig.DebugConsole)
                {
                    PInvokeHelpers.AllocConsole();
                }

                // init active display currency after config load
                ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

                // #2 then parse args
                var commandLineArgs = new CommandLineParser(argv);

                Helpers.ConsolePrint("NICEHASH", "Starting up NiceHashMiner v" + Application.ProductVersion);

                if (!pathSet)
                {
                    Helpers.ConsolePrint("NICEHASH", "Path not set to executable");
                }

                /* Preset language to RU and icence aggreement */
                ConfigManager.InitializeConfig();
                ConfigManager.GeneralConfig.agreedWithTOS = Globals.CurrentTosVer;
                ConfigManager.GeneralConfig.SetDefaults();
                ConfigManager.GeneralConfigFileCommit();
                ConfigManager.HideTrayIcon         = commandLineArgs.hideTrayIcon;
                ConfigManager.HideEmail            = commandLineArgs.hideEmail;
                ConfigManager.TestDriverUpdateForm = commandLineArgs.testDriverUpdateForm;


                var tosChecked = ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer;
                if (!tosChecked || !ConfigManager.GeneralConfigIsFileExist() && !commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH",
                                         "No config file found. Running NiceHash Miner Legacy for the first time. Choosing a default language.");
                    Application.Run(new Form_ChooseLanguage());
                }


                // Init languages
                International.Initialize(ConfigManager.GeneralConfig.Language);

                if (commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH", "Language is overwritten by command line parameter (-lang).");
                    International.Initialize(commandLineArgs.LangValue);
                    ConfigManager.GeneralConfig.Language = commandLineArgs.LangValue;
                }

                if (ConfigManager.GeneralConfig.Account == null || ConfigManager.GeneralConfig.WorkerName == "")
                {
                    Application.Run(new Form_Authorization());
                }
                else
                {
                    WebAPI.UpdateMachineInfo(ConfigManager.GeneralConfig.WorkerName);
                }

                // check WMI
                if (ConfigManager.GeneralConfig.Account != null)
                {
                    if (Helpers.IsWmiEnabled())
                    {
                        if (ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer)
                        {
                            while (true)
                            {
                                Application.Run(new Form_Main());
                                if (ConfigManager.GeneralConfig.Account == null)
                                {
                                    Application.Run(new Form_Authorization());
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(International.GetText("Program_WMI_Error_Text"),
                                        International.GetText("Program_WMI_Error_Title"),
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Вы должны сначала авторизоваться в системе!", "Ошибка",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #22
0
        public static bool CreateDAGFile(bool HideWindow, string worker)
        {
            try
            {
                if (!GetCurrentBlock(worker))
                {
                    throw new Exception("GetCurrentBlock returns null..");
                }

                // Check if dag-dir exist to avoid ethminer from crashing
                Helpers.ConsolePrint("Ethereum", "Creating DAG directory for " + worker + "..");
                if (!CreateDAGDirectory(worker))
                {
                    throw new Exception("[" + worker + "] Cannot create directory for DAG files.");
                }

                if (worker.Equals("NVIDIA3.x"))
                {
                    if (Directory.Exists(Config.ConfigData.DAGDirectory + "\\NVIDIA5.x"))
                    {
                        string src = Config.ConfigData.DAGDirectory + "\\NVIDIA5.x";
                        foreach (var file in Directory.GetFiles(src))
                        {
                            string dest = Path.Combine(Config.ConfigData.DAGDirectory + "\\" + worker, Path.GetFileName(file));
                            if (file.Contains("full") && !File.Exists(dest))
                            {
                                File.Copy(file, dest, false);
                            }
                        }
                    }
                }
                else if (worker.Equals("AMD_OpenCL"))
                {
                    if (Directory.Exists(Config.ConfigData.DAGDirectory + "\\NVIDIA5.x"))
                    {
                        string src = Config.ConfigData.DAGDirectory + "\\NVIDIA5.x";
                        foreach (var file in Directory.GetFiles(src))
                        {
                            string dest = Path.Combine(Config.ConfigData.DAGDirectory + "\\" + worker, Path.GetFileName(file));
                            if (file.Contains("full") && !File.Exists(dest))
                            {
                                File.Copy(file, dest, false);
                            }
                        }
                    }
                    else if (Directory.Exists(Config.ConfigData.DAGDirectory + "\\NVIDIA3.x"))
                    {
                        string src = Config.ConfigData.DAGDirectory + "\\NVIDIA3.x";
                        foreach (var file in Directory.GetFiles(src))
                        {
                            string dest = Path.Combine(Config.ConfigData.DAGDirectory + "\\" + worker, Path.GetFileName(file));
                            if (file.Contains("full") && !File.Exists(dest))
                            {
                                File.Copy(file, dest, false);
                            }
                        }
                    }
                }

                Helpers.ConsolePrint("Ethereum", "Creating DAG file for " + worker + "..");

                Process P = new Process();
                P.StartInfo.FileName        = EtherMinerPath;
                P.StartInfo.Arguments       = " --dag-dir " + Config.ConfigData.DAGDirectory + "\\" + worker + " --create-dag " + CurrentBlockNum;
                P.StartInfo.CreateNoWindow  = HideWindow;
                P.StartInfo.UseShellExecute = !HideWindow;
                P.Start();
                P.WaitForExit();

                P.Close();
                P = null;
            }
            catch (Exception e)
            {
                Helpers.ConsolePrint("Ethereum", "Exception: " + e.ToString());
                return(false);
            }

            return(true);
        }
Beispiel #23
0
        protected async Task <string> GetAPIDataAsync(int port, string DataToSend, bool exitHack = false, bool overrideLoop = false)
        {
            string ResponseFromServer = null;

            try
            {
                TcpClient tcpc     = new TcpClient("127.0.0.1", port);
                var       nwStream = tcpc.GetStream();

                byte[] BytesToSend = ASCIIEncoding.ASCII.GetBytes(DataToSend);
                await nwStream.WriteAsync(BytesToSend, 0, BytesToSend.Length);

                byte[] IncomingBuffer = new byte[tcpc.ReceiveBufferSize];
                int    prevOffset     = -1;
                int    offset         = 0;
                bool   fin            = false;

                while (!fin && tcpc.Client.Connected)
                {
                    int r = await nwStream.ReadAsync(IncomingBuffer, offset, tcpc.ReceiveBufferSize - offset);

                    for (int i = offset; i < offset + r; i++)
                    {
                        if (IncomingBuffer[i] == 0x7C || IncomingBuffer[i] == 0x00 ||
                            (i > 2 && IsApiEof(IncomingBuffer[i - 2], IncomingBuffer[i - 1], IncomingBuffer[i])) ||
                            overrideLoop)
                        {
                            fin = true;
                            break;
                        }
                        // Not working
                        //if (IncomingBuffer[i] == 0x5d || IncomingBuffer[i] == 0x5e) {
                        //    fin = true;
                        //    break;
                        //}
                    }
                    offset += r;
                    if (exitHack)
                    {
                        if (prevOffset == offset)
                        {
                            fin = true;
                            break;
                        }
                        prevOffset = offset;
                    }
                }

                tcpc.Close();

                if (offset > 0)
                {
                    ResponseFromServer = ASCIIEncoding.ASCII.GetString(IncomingBuffer);
                }
            }
            catch (Exception ex)
            {
                Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " GetAPIData reason: " + ex.Message);
                return(null);
            }

            return(ResponseFromServer);
        }
        // This is a single shot _benchmarkTimer
        private void StartupTimer_Tick(object sender, EventArgs e)
        {
            StartupTimer.Stop();
            StartupTimer = null;

            // Internals Init
            // TODO add loading step
            MinersSettingsManager.Init();

            if (!Helpers.Is45NetOrHigher())
            {
                MessageBox.Show(International.GetText("NET45_Not_Installed_msg"),
                                International.GetText("Warning_with_Exclamation"),
                                MessageBoxButtons.OK);

                this.Close();
                return;
            }

            if (!Helpers.Is64BitOperatingSystem)
            {
                MessageBox.Show(International.GetText("Form_Main_x64_Support_Only"),
                                International.GetText("Warning_with_Exclamation"),
                                MessageBoxButtons.OK);

                this.Close();
                return;
            }

            // 3rdparty miners check scope #1
            {
                // check if setting set
                if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.NOT_SET)
                {
                    // Show TOS
                    Form tos = new Form_3rdParty_TOS();
                    tos.ShowDialog(this);
                }
            }

            // Query Avaliable ComputeDevices
            ComputeDeviceManager.Query.QueryDevices(LoadingScreen);
            _isDeviceDetectionInitialized = true;

            /////////////////////////////////////////////
            /////// from here on we have our devices and Miners initialized
            ConfigManager.AfterDeviceQueryInitialization();
            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SaveConfig"));

            // All devices settup should be initialized in AllDevices
            devicesListViewEnableControl1.ResetComputeDevices(ComputeDeviceManager.Avaliable.AllAvaliableDevices);
            // set properties after
            devicesListViewEnableControl1.SaveToGeneralConfig = true;

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_CheckLatestVersion"));

            MinerStatsCheck          = new Timer();
            MinerStatsCheck.Tick    += MinerStatsCheck_Tick;
            MinerStatsCheck.Interval = ConfigManager.GeneralConfig.MinerAPIQueryInterval * 1000;

            SMAMinerCheck          = new Timer();
            SMAMinerCheck.Tick    += SMAMinerCheck_Tick;
            SMAMinerCheck.Interval = ConfigManager.GeneralConfig.SwitchMinSecondsFixed * 1000 + R.Next(ConfigManager.GeneralConfig.SwitchMinSecondsDynamic * 1000);
            if (ComputeDeviceManager.Group.ContainsAMD_GPUs)
            {
                SMAMinerCheck.Interval = (ConfigManager.GeneralConfig.SwitchMinSecondsAMD + ConfigManager.GeneralConfig.SwitchMinSecondsFixed) * 1000 + R.Next(ConfigManager.GeneralConfig.SwitchMinSecondsDynamic * 1000);
            }

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_GetNiceHashSMA"));
            // Init ws connection
            NiceHashStats.OnBalanceUpdate         += BalanceCallback;
            NiceHashStats.OnSMAUpdate             += SMACallback;
            NiceHashStats.OnVersionUpdate         += VersionUpdateCallback;
            NiceHashStats.OnConnectionLost        += ConnectionLostCallback;
            NiceHashStats.OnConnectionEstablished += ConnectionEstablishedCallback;
            NiceHashStats.OnVersionBurn           += VersionBurnCallback;
            NiceHashStats.StartConnection(Links.NHM_Socket_Address);

            // increase timeout
            if (Globals.IsFirstNetworkCheckTimeout)
            {
                while (!Helpers.WebRequestTestGoogle() && Globals.FirstNetworkCheckTimeoutTries > 0)
                {
                    --Globals.FirstNetworkCheckTimeoutTries;
                }
            }

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_GetBTCRate"));

            BitcoinExchangeCheck          = new Timer();
            BitcoinExchangeCheck.Tick    += BitcoinExchangeCheck_Tick;
            BitcoinExchangeCheck.Interval = 1000 * 3601; // every 1 hour and 1 second
            BitcoinExchangeCheck.Start();
            BitcoinExchangeCheck_Tick(null, null);

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SetEnvironmentVariable"));
            Helpers.SetDefaultEnvironmentVariables();

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SetWindowsErrorReporting"));

            Helpers.DisableWindowsErrorReporting(ConfigManager.GeneralConfig.DisableWindowsErrorReporting);

            LoadingScreen.IncreaseLoadCounter();
            if (ConfigManager.GeneralConfig.NVIDIAP0State)
            {
                LoadingScreen.SetInfoMsg(International.GetText("Form_Main_loadtext_NVIDIAP0State"));
                try {
                    ProcessStartInfo psi = new ProcessStartInfo();
                    psi.FileName        = "nvidiasetp0state.exe";
                    psi.Verb            = "runas";
                    psi.UseShellExecute = true;
                    psi.CreateNoWindow  = true;
                    Process p = Process.Start(psi);
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Helpers.ConsolePrint("NICEHASH", "nvidiasetp0state returned error code: " + p.ExitCode.ToString());
                    }
                    else
                    {
                        Helpers.ConsolePrint("NICEHASH", "nvidiasetp0state all OK");
                    }
                } catch (Exception ex) {
                    Helpers.ConsolePrint("NICEHASH", "nvidiasetp0state error: " + ex.Message);
                }
            }

            LoadingScreen.FinishLoad();

            bool runVCRed = !MinersExistanceChecker.IsMinersBinsInit() && !ConfigManager.GeneralConfig.DownloadInit;

            // standard miners check scope
            {
                // check if download needed
                if (!MinersExistanceChecker.IsMinersBinsInit() && !ConfigManager.GeneralConfig.DownloadInit)
                {
                    Form_Loading downloadUnzipForm = new Form_Loading(new MinersDownloader(MinersDownloadManager.StandardDlSetup));
                    SetChildFormCenter(downloadUnzipForm);
                    downloadUnzipForm.ShowDialog();
                }
                // check if files are mising
                if (!MinersExistanceChecker.IsMinersBinsInit())
                {
                    var result = MessageBox.Show(International.GetText("Form_Main_bins_folder_files_missing"),
                                                 International.GetText("Warning_with_Exclamation"),
                                                 MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        ConfigManager.GeneralConfig.DownloadInit = false;
                        ConfigManager.GeneralConfigFileCommit();
                        Process PHandle = new Process();
                        PHandle.StartInfo.FileName = Application.ExecutablePath;
                        PHandle.Start();
                        Close();
                        return;
                    }
                }
                else if (!ConfigManager.GeneralConfig.DownloadInit)
                {
                    // all good
                    ConfigManager.GeneralConfig.DownloadInit = true;
                    ConfigManager.GeneralConfigFileCommit();
                }
            }
            // 3rdparty miners check scope #2
            {
                // check if download needed
                if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.YES)
                {
                    if (!MinersExistanceChecker.IsMiners3rdPartyBinsInit() && !ConfigManager.GeneralConfig.DownloadInit3rdParty)
                    {
                        Form_Loading download3rdPartyUnzipForm = new Form_Loading(new MinersDownloader(MinersDownloadManager.ThirdPartyDlSetup));
                        SetChildFormCenter(download3rdPartyUnzipForm);
                        download3rdPartyUnzipForm.ShowDialog();
                    }
                    // check if files are mising
                    if (!MinersExistanceChecker.IsMiners3rdPartyBinsInit())
                    {
                        var result = MessageBox.Show(International.GetText("Form_Main_bins_folder_files_missing"),
                                                     International.GetText("Warning_with_Exclamation"),
                                                     MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (result == DialogResult.Yes)
                        {
                            ConfigManager.GeneralConfig.DownloadInit3rdParty = false;
                            ConfigManager.GeneralConfigFileCommit();
                            Process PHandle = new Process();
                            PHandle.StartInfo.FileName = Application.ExecutablePath;
                            PHandle.Start();
                            Close();
                            return;
                        }
                    }
                    else if (!ConfigManager.GeneralConfig.DownloadInit3rdParty)
                    {
                        // all good
                        ConfigManager.GeneralConfig.DownloadInit3rdParty = true;
                        ConfigManager.GeneralConfigFileCommit();
                    }
                }
            }

            if (runVCRed)
            {
                Helpers.InstallVcRedist();
            }

            // no bots please
            if (ConfigManager.GeneralConfigHwidLoadFromFile() && !ConfigManager.GeneralConfigHwidOK())
            {
                var result = MessageBox.Show("NiceHash Miner Legacy has detected change of hardware ID. If you did not download and install NiceHash Miner Legacy, your computer may be compromised. In that case, we suggest you to install an antivirus program or reinstall your Windows.\r\n\r\nContinue with NiceHash Miner Legacy?",
                                             //International.GetText("Form_Main_msgbox_anti_botnet_msgbox"),
                                             International.GetText("Warning_with_Exclamation"),
                                             MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == System.Windows.Forms.DialogResult.No)
                {
                    Close();
                    return;
                }
                else
                {
                    // users agrees he installed it so commit changes
                    ConfigManager.GeneralConfigFileCommit();
                }
            }
            else
            {
                if (ConfigManager.GeneralConfig.AutoStartMining)
                {
                    // well this is started manually as we want it to start at runtime
                    IsManuallyStarted = true;
                    if (StartMining(true) != StartMiningReturnType.StartMining)
                    {
                        IsManuallyStarted = false;
                        StopMining();
                    }
                }
            }
        }
Beispiel #25
0
 private static void ErrorCallback(object sender, WebSocketSharp.ErrorEventArgs e)
 {
     Helpers.ConsolePrint("SOCKET", e.ToString());
 }
Beispiel #26
0
        protected async Task <ApiData> GetSummaryCpuAsync(string method = "", bool overrideLoop = false)
        {
            var ad = new ApiData(MiningSetup.CurrentAlgorithmType);

            try
            {
                CurrentMinerReadStatus = MinerApiReadStatus.WAIT;
                var dataToSend = GetHttpRequestNhmAgentStrin(method);
                var respStr    = await GetApiDataAsync(ApiPort, dataToSend);

                if (string.IsNullOrEmpty(respStr))
                {
                    CurrentMinerReadStatus = MinerApiReadStatus.NETWORK_EXCEPTION;
                    throw new Exception("Response is empty!");
                }

                if (respStr.IndexOf("HTTP/1.1 200 OK") > -1)
                {
                    respStr = respStr.Substring(respStr.IndexOf(HttpHeaderDelimiter) + HttpHeaderDelimiter.Length);
                }
                else
                {
                    throw new Exception("Response not HTTP formed! " + respStr);
                }

                dynamic resp = JsonConvert.DeserializeObject(respStr);

                if (resp != null)
                {
                    JArray totals = resp.hashrate.total;
                    foreach (var total in totals)
                    {
                        if (total.Value <string>() == null)
                        {
                            continue;
                        }
                        ad.Speed = total.Value <double>();
                        break;
                    }

                    if (ad.Speed == 0)
                    {
                        CurrentMinerReadStatus = MinerApiReadStatus.READ_SPEED_ZERO;
                    }
                    else
                    {
                        CurrentMinerReadStatus = MinerApiReadStatus.GOT_READ;
                    }
                }
                else
                {
                    throw new Exception($"Response does not contain speed data: {respStr.Trim()}");
                }
            }
            catch (Exception ex)
            {
                Helpers.ConsolePrint(MinerTag(), ex.Message);
            }

            return(ad);
        }
Beispiel #27
0
        private void InitiateBenchmark()
        {
            if (listView1.Items.Count > index)
            {
                ListViewItem lvi = listView1.Items[index];
                index++;

                if (!lvi.Checked)
                {
                    InitiateBenchmark();
                    return;
                }

                Miner m = lvi.Tag as Miner;
                int   i = (int)lvi.SubItems[2].Tag;
                //lvi.SubItems[3].Text = "Please wait...";
                inBenchmark           = true;
                CurrentlyBenchmarking = m;

                if (m is cpuminer)
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsCPU[TimeIndex];
                    lvi.SubItems[3].Text = String.Format(International.GetText("form2_listView_WaitSeconds"), Time);
                }
                else if (m is ccminer)
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsNVIDIA[TimeIndex];

                    if (lvi.SubItems[2].Text.Equals("daggerhashimoto"))
                    {
                        lvi.SubItems[3].Text = International.GetText("form2_listView_WaitForEth");
                    }
                    else
                    {
                        lvi.SubItems[3].Text = String.Format(International.GetText("form2_listView_WaitSeconds"), Time);
                    }
                }
                else
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsAMD[TimeIndex] / 60;

                    // add an aditional minute if second is not 0
                    if (DateTime.Now.Second != 0)
                    {
                        Time += 1;
                    }

                    if (lvi.SubItems[2].Text.Equals("daggerhashimoto"))
                    {
                        lvi.SubItems[3].Text = International.GetText("form2_listView_WaitForEth");
                    }
                    else
                    {
                        lvi.SubItems[3].Text = String.Format(International.GetText("form2_listView_WaitMinutes"), Time);
                    }
                }

                m.BenchmarkStart(i, Time, BenchmarkCompleted, lvi);
            }
            else
            {
                // average all cpu benchmarks
                if (Form1.Miners[0] is cpuminer)
                {
                    Helpers.ConsolePrint("BENCHMARK", "Calculating average CPU speeds:");

                    double[] Speeds = new double[Form1.Miners[0].SupportedAlgorithms.Length];
                    int[]    MTaken = new int[Form1.Miners[0].SupportedAlgorithms.Length];

                    foreach (ListViewItem lvi in listView1.Items)
                    {
                        if (lvi.Tag is cpuminer)
                        {
                            Miner m = lvi.Tag as Miner;
                            int   i = (int)lvi.SubItems[2].Tag;
                            if (m.SupportedAlgorithms[i].BenchmarkSpeed > 0)
                            {
                                Speeds[i] += m.SupportedAlgorithms[i].BenchmarkSpeed;
                                MTaken[i]++;
                            }
                        }
                    }

                    for (int i = 0; i < Speeds.Length; i++)
                    {
                        if (MTaken[i] > 0)
                        {
                            Speeds[i] /= MTaken[i];
                        }
                        Helpers.ConsolePrint("BENCHMARK", Form1.Miners[0].SupportedAlgorithms[i].NiceHashName + " average speed: " + Form1.Miners[0].PrintSpeed(Speeds[i]));

                        foreach (Miner m in Form1.Miners)
                        {
                            if (m is cpuminer)
                            {
                                m.SupportedAlgorithms[i].BenchmarkSpeed = Speeds[i];
                            }
                        }
                    }
                }

                foreach (ListViewItem lvi in listView1.Items)
                {
                    Miner m = lvi.Tag as Miner;
                    int   i = (int)lvi.SubItems[2].Tag;
                    lvi.SubItems[3].Text = m.PrintSpeed(m.SupportedAlgorithms[i].BenchmarkSpeed);
                }

                Config.RebuildGroups();

                buttonStartBenchmark.Enabled     = true;
                buttonStopBenchmark.Enabled      = false;
                buttonReset.Enabled              = true;
                buttonClose.Enabled              = true;
                buttonCheckProfitability.Enabled = true;
                buttonSubmitHardware.Enabled     = true;
            }
        }
Beispiel #28
0
        protected virtual Process BenchmarkStartProcess(string commandLine)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            Helpers.ConsolePrint(MinerTag(), "Starting benchmark: " + commandLine);

            var benchmarkHandle = new Process
            {
                StartInfo =
                {
                    FileName = MiningSetup.MinerPath
                }
            };


            // sgminer quickfix
            if (this is Sgminer)
            {
                BenchmarkProcessPath = "cmd / " + benchmarkHandle.StartInfo.FileName;
                benchmarkHandle.StartInfo.FileName = "cmd";
            }
            else
            {
                BenchmarkProcessPath = benchmarkHandle.StartInfo.FileName;
                Helpers.ConsolePrint(MinerTag(), "Using miner: " + benchmarkHandle.StartInfo.FileName);
                benchmarkHandle.StartInfo.WorkingDirectory = WorkingDirectory;
            }

            // set sys variables
            if (MinersSettingsManager.MinerSystemVariables.ContainsKey(Path))
            {
                foreach (var kvp in MinersSettingsManager.MinerSystemVariables[Path])
                {
                    var envName  = kvp.Key;
                    var envValue = kvp.Value;
                    benchmarkHandle.StartInfo.EnvironmentVariables[envName] = envValue;
                }
            }

            benchmarkHandle.StartInfo.Arguments              = commandLine;
            benchmarkHandle.StartInfo.UseShellExecute        = false;
            benchmarkHandle.StartInfo.RedirectStandardError  = true;
            benchmarkHandle.StartInfo.RedirectStandardOutput = true;
            benchmarkHandle.StartInfo.CreateNoWindow         = true;
            benchmarkHandle.OutputDataReceived += BenchmarkOutputErrorDataReceived;
            benchmarkHandle.ErrorDataReceived  += BenchmarkOutputErrorDataReceived;
            benchmarkHandle.Exited             += BenchmarkHandle_Exited;

            Ethlargement.CheckAndStart(MiningSetup);

            if (!benchmarkHandle.Start())
            {
                return(null);
            }

            _currentPidData = new MinerPidData
            {
                MinerBinPath = benchmarkHandle.StartInfo.FileName,
                Pid          = benchmarkHandle.Id
            };
            _allPidData.Add(_currentPidData);

            return(benchmarkHandle);
        }
Beispiel #29
0
        protected string GetAPIData(int port, string DataToSend, bool exitHack = false)
        {
            string ResponseFromServer = null;

            try
            {
                TcpClient tcpc = new TcpClient("127.0.0.1", port);

                byte[] BytesToSend = ASCIIEncoding.ASCII.GetBytes(DataToSend);
                tcpc.Client.Send(BytesToSend);

                byte[] IncomingBuffer = new byte[5000];
                int    prevOffset     = -1;
                int    offset         = 0;
                bool   fin            = false;

                while (!fin && tcpc.Client.Connected)
                {
                    int r = tcpc.Client.Receive(IncomingBuffer, offset, 5000 - offset, SocketFlags.None);
                    for (int i = offset; i < offset + r; i++)
                    {
                        if (IncomingBuffer[i] == 0x7C || IncomingBuffer[i] == 0x00 ||
                            (i > 0 && this is XmrStackCPUMiner &&
                             IncomingBuffer[i] == 0x7d && IncomingBuffer[i - 1] == 0x7d))
                        {
                            // Workaround for new XMR-STAK api
                            fin = true;
                            break;
                        }
                        // Not working
                        //if (IncomingBuffer[i] == 0x5d || IncomingBuffer[i] == 0x5e) {
                        //    fin = true;
                        //    break;
                        //}
                    }
                    offset += r;
                    if (exitHack)
                    {
                        if (prevOffset == offset)
                        {
                            fin = true;
                            break;
                        }
                        prevOffset = offset;
                    }
                }

                tcpc.Close();

                if (offset > 0)
                {
                    ResponseFromServer = ASCIIEncoding.ASCII.GetString(IncomingBuffer);
                }
            }
            catch (Exception ex)
            {
                Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " GetAPIData reason: " + ex.Message);
                return(null);
            }

            return(ResponseFromServer);
        }
Beispiel #30
0
        static void Main(string[] argv)
        {
            // Set working directory to exe
            var pathSet = false;
            var path    = Path.GetDirectoryName(Application.ExecutablePath);

            if (path != null)
            {
                Environment.CurrentDirectory = path;
                pathSet = true;
            }

            // Add common folder to path for launched processes
            var pathVar = Environment.GetEnvironmentVariable("PATH");

            pathVar += ";" + Path.Combine(Environment.CurrentDirectory, "common");
            Environment.SetEnvironmentVariable("PATH", pathVar);


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            //Console.OutputEncoding = System.Text.Encoding.Unicode;
            // #0 set this first so data parsing will work correctly
            Globals.JsonSettings = new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                Culture = CultureInfo.InvariantCulture
            };

            // #1 first initialize config
            ConfigManager.InitializeConfig();

            // #2 check if multiple instances are allowed
            var startProgram = true;

            if (ConfigManager.GeneralConfig.AllowMultipleInstances == false)
            {
                try
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            startProgram = false;
                        }
                    }
                }
                catch { }
            }

            if (startProgram)
            {
                if (ConfigManager.GeneralConfig.LogToFile)
                {
                    Logger.ConfigureWithFile();
                }

                if (ConfigManager.GeneralConfig.DebugConsole)
                {
                    PInvokeHelpers.AllocConsole();
                }
                //**
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 4)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (File.Exists("internals\\MinerOptionPackage_glg.json"))
                    {
                        File.Delete("internals\\MinerOptionPackage_glg.json");
                    }

                    if (File.Exists("internals\\MinerOptionPackage_ClaymoreDual.json"))
                    {
                        File.Delete("internals\\MinerOptionPackage_ClaymoreDual.json");
                    }

                    if (File.Exists("bin\\ccminer_klaust\\ccminer.exe"))
                    {
                        File.Delete("bin\\ccminer_klaust\\ccminer.exe");
                    }
                    ConfigManager.GeneralConfig.ForkFixVersion = 4;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 4.1)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (File.Exists("internals\\MinerOptionPackage_ClaymoreDual.json"))
                    {
                        File.Delete("internals\\MinerOptionPackage_ClaymoreDual.json");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 4.1;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 5)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 5;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 6)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 6;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 7)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 7;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 8)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 8;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 8.2)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 8.2;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 9)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 9;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 9.1)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    if (File.Exists("bin_3rdparty\\t-rex\\t-rex.exe"))
                    {
                        File.Delete("bin_3rdparty\\t-rex\\t-rex.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 9.1;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 9.2)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    if (File.Exists("bin_3rdparty\\t-rex\\t-rex.exe"))
                    {
                        File.Delete("bin_3rdparty\\t-rex\\t-rex.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 9.2;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 9.3)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    if (File.Exists("bin_3rdparty\\t-rex\\t-rex.exe"))
                    {
                        File.Delete("bin_3rdparty\\t-rex\\t-rex.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 9.3;
                }

                //**

                // init active display currency after config load
                ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

                // #2 then parse args
                var commandLineArgs = new CommandLineParser(argv);

                Helpers.ConsolePrint("NICEHASH", "Starting up NiceHashMiner v" + Application.ProductVersion);

                if (!pathSet)
                {
                    Helpers.ConsolePrint("NICEHASH", "Path not set to executable");
                }

                var tosChecked = ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer;
                if (!tosChecked || !ConfigManager.GeneralConfigIsFileExist() && !commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH",
                                         "No config file found. Running NiceHash Miner Legacy for the first time. Choosing a default language.");
                    Application.Run(new Form_ChooseLanguage());
                }

                // Init languages
                International.Initialize(ConfigManager.GeneralConfig.Language);

                if (commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH", "Language is overwritten by command line parameter (-lang).");
                    International.Initialize(commandLineArgs.LangValue);
                    ConfigManager.GeneralConfig.Language = commandLineArgs.LangValue;
                }

                // check WMI
                if (Helpers.IsWmiEnabled())
                {
                    if (ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer)
                    {
                        Application.Run(new Form_Main());
                    }
                }
                else
                {
                    MessageBox.Show(International.GetText("Program_WMI_Error_Text"),
                                    International.GetText("Program_WMI_Error_Title"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }