Esempio n. 1
0
 private void OnNTMinerRootInited()
 {
     OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Access();
     NTMinerRoot.KernelDownloader = new KernelDownloader();
     Execute.OnUIThread(() => {
         Global.Logger.InfoDebugLine("new MainWindow");
         Window splashWindow    = MainWindow;
         MainWindow window      = new MainWindow();
         IMainWindow mainWindow = window;
         this.MainWindow        = window;
         this.MainWindow.Show();
         this.MainWindow.Activate();
         Global.Logger.InfoDebugLine("MainWindow showed");
         notifyIcon = new ExtendedNotifyIcon("pack://application:,,,/NTMiner;component/logo.ico");
         notifyIcon.Init();
         #region 处理显示主界面命令
         Global.Access <ShowMainWindowCommand>(
             Guid.Parse("01f3c467-f494-42b8-bcb5-848050df59f3"),
             "处理显示主界面命令",
             LogEnum.None,
             action: message => {
             Execute.OnUIThread(() => {
                 Dispatcher.Invoke((ThreadStart)mainWindow.ShowThisWindow);
             });
         });
         #endregion
         #region 处理重启NTMiner命令
         Global.Access <RestartNTMinerCommand>(
             Guid.Parse("d1712c1f-507c-496f-9da2-870cbd9fc57f"),
             "处理重启NTMiner命令",
             LogEnum.None,
             action: message => {
             List <string> args = CommandLineArgs.Args;
             if (message.IsWorkEdit)
             {
                 if (CommandLineArgs.IsWorkEdit && CommandLineArgs.WorkId == message.MineWorkId)
                 {
                     Execute.OnUIThread(() => {
                         Dispatcher.Invoke((ThreadStart)mainWindow.ShowThisWindow);
                     });
                     return;
                 }
                 if (!CommandLineArgs.IsControlCenter)
                 {
                     args.Add("--controlCenter");
                 }
             }
             if (message.MineWorkId != Guid.Empty)
             {
                 if (!CommandLineArgs.IsWorker)
                 {
                     args.Add("--workid=" + message.MineWorkId.ToString());
                 }
                 else
                 {
                     for (int i = 0; i < args.Count; i++)
                     {
                         if (args[i].StartsWith("--workid=", StringComparison.OrdinalIgnoreCase))
                         {
                             args[i] = "--workid=" + message.MineWorkId.ToString();
                             break;
                         }
                     }
                 }
             }
             else
             {
                 if (CommandLineArgs.IsWorker)
                 {
                     int workIdIndex = -1;
                     for (int i = 0; i < args.Count; i++)
                     {
                         if (args[i].ToLower().Contains("--workid="))
                         {
                             workIdIndex = i;
                             break;
                         }
                     }
                     if (workIdIndex != -1)
                     {
                         args.RemoveAt(workIdIndex);
                     }
                 }
             }
             NTMiner.Windows.Cmd.RunClose(ClientId.AppFileFullName, string.Join(" ", args));
             Current.MainWindow.Close();
         });
         #endregion
         try {
             NTMinerRoot.Current.Start();
         }
         catch (Exception ex) {
             Global.Logger.ErrorDebugLine(ex.Message, ex);
         }
         splashWindow?.Close();
         if (NTMinerRoot.Current.MinerProfile.IsAutoStart || CommandLineArgs.IsAutoStart)
         {
             Global.Logger.InfoDebugLine("自动开始挖矿倒计时");
             Views.Ucs.AutoStartCountdown.ShowDialog();
         }
     });
 }
Esempio n. 2
0
            // 创建管道,将输出通过管道转送到日志文件,然后读取日志文件内容打印到控制台
            private static void CreatePipProcess(IMineContext mineContext, string cmdLine)
            {
                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES();
                IntPtr hReadOut, hWriteOut;

                //set the bInheritHandle flag so pipe handles are inherited

                saAttr.bInheritHandle       = true;
                saAttr.lpSecurityDescriptor = IntPtr.Zero;
                saAttr.length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
                saAttr.lpSecurityDescriptor = IntPtr.Zero;
                //get handle to current stdOut

                bool bret;

                IntPtr mypointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STARTUPINFO)));

                Marshal.StructureToPtr(saAttr, mypointer, true);
                bret = CreatePipe(out hReadOut, out hWriteOut, mypointer, 0);
                //ensure the read handle to pipe for stdout is not inherited
                SetHandleInformation(hReadOut, HANDLE_FLAG_INHERIT, 0);
                ////Create pipe for the child process's STDIN
                STARTUPINFO lpStartupInfo = new STARTUPINFO {
                    cb          = (uint)Marshal.SizeOf(typeof(STARTUPINFO)),
                    dwFlags     = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW,
                    wShowWindow = SW_HIDE, // SW_HIDE; //SW_SHOW
                    hStdOutput  = hWriteOut,
                    hStdError   = hWriteOut,
                    hStdInput   = IntPtr.Zero
                };
                PROCESS_INFORMATION lpProcessInformation;

                if (CreateProcess(
                        lpApplicationName: null,
                        lpCommandLine: new StringBuilder(cmdLine),
                        lpProcessAttributes: IntPtr.Zero,
                        lpThreadAttributes: IntPtr.Zero,
                        bInheritHandles: true,
                        dwCreationFlags: NORMAL_PRIORITY_CLASS,
                        lpEnvironment: IntPtr.Zero,
                        lpCurrentDirectory: null,
                        lpStartupInfo: ref lpStartupInfo,
                        lpProcessInformation: out lpProcessInformation))
                {
                    if (bret == false)
                    {
                        int lasterr = Marshal.GetLastWin32Error();
                    }
                    else
                    {
                        Bus.DelegateHandler <MineStopedEvent> closeHandle = null;
                        bool isHWriteOutHasClosed = false;
                        Daemon(mineContext, () => {
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            Global.UnAccess(closeHandle);
                        });
                        closeHandle = Global.Access <MineStopedEvent>(
                            Guid.Parse("91642027-fd28-4bdd-a05a-31caac6609b1"),
                            "挖矿停止后关闭非托管的日志句柄",
                            LogEnum.Log,
                            action: message => {
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            Global.UnAccess(closeHandle);
                        });
                        string pipLogFileFullName = Path.Combine(SpecialPath.LogsDirFullName, mineContext.PipeFileName);
                        Task.Factory.StartNew(() => {
                            using (FileStream fs = new FileStream(pipLogFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                                using (StreamReader sr = new StreamReader(fs)) {
                                    byte[] buffer = new byte[1024];
                                    int ret;
                                    // Read会阻塞,直到读取到字符或者hWriteOut被关闭
                                    while ((ret = Read(buffer, 0, buffer.Length, hReadOut)) > 0)
                                    {
                                        fs.Write(buffer, 0, ret);
                                        if (buffer[ret - 1] == '\r' || buffer[ret - 1] == '\n')
                                        {
                                            fs.Flush();
                                        }
                                    }
                                }
                            CloseHandle(hReadOut);
                        });
                        Task.Factory.StartNew(() => {
                            ReadPrintLoopLogFile(mineContext, pipLogFileFullName);
                        });
                    }
                }
                else
                {
                    Global.Logger.WarnWriteLine("内核启动失败,请重试");
                }
            }
Esempio n. 3
0
 public void Init(Action callback)
 {
     if (!this._isInited)
     {
         lock (this._locker) {
             if (!this._isInited)
             {
                 string rawNTMinerJson = string.Empty;
                 if (File.Exists(SpecialPath.LocalJsonFileFullName))
                 {
                     rawNTMinerJson = File.ReadAllText(SpecialPath.LocalJsonFileFullName);
                 }
                 string rawLangJson = string.Empty;
                 if (File.Exists(ClientId.LocalLangJsonFileFullName))
                 {
                     rawLangJson = File.ReadAllText(ClientId.LocalLangJsonFileFullName);
                 }
                 if (CommandLineArgs.IsSkipDownloadJson)
                 {
                     DoInit(rawNTMinerJson, rawLangJson, callback);
                     Global.Access <HasBoot5SecondEvent>(
                         Guid.Parse("546CCF96-D87E-4436-B236-0A9416DFE28D"),
                         "Debug打印",
                         LogEnum.Log,
                         action: (message) => {
                         Global.Logger.OkDebugLine("已跳过从服务器下载Json");
                     });
                     _isInited = true;
                 }
                 else
                 {
                     Task t1 = Task.Factory.StartNew(() => {
                         try {
                             using (WebClient webClient = new WebClient()) {
                                 string jsonUrl = "https://minerjson.oss-cn-beijing.aliyuncs.com/" + ClientId.ServerJsonFileName;
                                 Global.Logger.InfoDebugLine("下载:" + jsonUrl);
                                 byte[] data    = webClient.DownloadData(jsonUrl);
                                 rawNTMinerJson = System.Text.Encoding.UTF8.GetString(data);
                             }
                         }
                         catch (Exception e) {
                             Global.Logger.ErrorDebugLine(e.Message, e);
                         }
                     });
                     Task t2 = Task.Factory.StartNew(() => {
                         try {
                             using (WebClient webClient = new WebClient()) {
                                 string jsonUrl = "https://minerjson.oss-cn-beijing.aliyuncs.com/" + ClientId.ServerLangJsonFileName;
                                 Global.Logger.InfoDebugLine("下载:" + jsonUrl);
                                 byte[] data = webClient.DownloadData(jsonUrl);
                                 rawLangJson = System.Text.Encoding.UTF8.GetString(data);
                             }
                         }
                         catch (Exception e) {
                             Global.Logger.ErrorDebugLine(e.Message, e);
                         }
                     });
                     Task.Factory.StartNew(() => {
                         if (Task.WaitAll(new Task[] { t1, t2 }, 30 * 1000))
                         {
                             DoInit(rawNTMinerJson, rawLangJson, callback);
                         }
                         else
                         {
                             Global.Logger.InfoDebugLine("启动json下载超时");
                             DoInit(rawNTMinerJson, rawLangJson, callback);
                         }
                         _isInited = true;
                     });
                 }
             }
         }
     }
 }
Esempio n. 4
0
 protected override void OnStartup(StartupEventArgs e)
 {
     Global.Logger.InfoDebugLine("App.OnStartup start");
     RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
     try {
         appMutex = new Mutex(true, _appPipName, out createdNew);
     }
     catch (Exception) {
         createdNew = false;
     }
     if (createdNew)
     {
         Vms.AppStatic.IsMinerClient = false;
         Global.Logger.InfoDebugLine("new SplashWindow");
         SplashWindow splashWindow = new SplashWindow();
         splashWindow.Show();
         NTMinerRoot.Current.Init(() => {
             NTMinerRoot.KernelDownloader = new KernelDownloader();
             Execute.OnUIThread(() => {
                 bool?result = true;
                 if (string.IsNullOrEmpty(Server.LoginName) || string.IsNullOrEmpty(Server.Password))
                 {
                     LoginWindow loginWindow = new LoginWindow();
                     splashWindow.Hide();
                     result = loginWindow.ShowDialog();
                 }
                 if (result.HasValue && result.Value)
                 {
                     Global.Logger.InfoDebugLine("new MainWindow");
                     ControlCenterWindow window = new ControlCenterWindow();
                     IMainWindow mainWindow     = window;
                     this.MainWindow            = window;
                     this.MainWindow.Show();
                     this.MainWindow.Activate();
                     Global.Logger.InfoDebugLine("MainWindow showed");
                     notifyIcon = new ExtendedNotifyIcon("pack://application:,,,/ControlCenterApp;component/logo.ico");
                     notifyIcon.Init();
                     #region 处理显示主界面命令
                     Global.Access <ShowMainWindowCommand>(
                         Guid.Parse("01f3c467-f494-42b8-bcb5-848050df59f3"),
                         "处理显示主界面命令",
                         LogEnum.None,
                         action: message => {
                         Execute.OnUIThread(() => {
                             Dispatcher.Invoke((ThreadStart)mainWindow.ShowThisWindow);
                         });
                     });
                     #endregion
                 }
                 splashWindow?.Close();
             });
         });
     }
     else
     {
         try {
             AppHelper.ShowMainWindow(this, _appPipName);
         }
         catch (Exception) {
             DialogWindow.ShowDialog(message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。", title: "alert", icon: "Icon_Error");
             Process   currentProcess = Process.GetCurrentProcess();
             Process[] processes      = Process.GetProcessesByName(currentProcess.ProcessName);
             foreach (var process in processes)
             {
                 if (process.Id != currentProcess.Id)
                 {
                     NTMiner.Windows.TaskKill.Kill(process.Id);
                 }
             }
         }
     }
     base.OnStartup(e);
     Global.Logger.InfoDebugLine("App.OnStartup end");
 }
Esempio n. 5
0
        public void Start()
        {
            Global.Logger.InfoDebugLine("开始启动Wcf服务");
            string      baseUrl = $"http://{Global.Localhost}:{Global.ClientPort}/";
            ServiceHost minerClientServiceHost = new ServiceHost(typeof(Core.Impl.MinerClientService));

            minerClientServiceHost.AddServiceEndpoint(typeof(IMinerClientService), ChannelFactory.BasicHttpBinding, new Uri(new Uri(baseUrl), nameof(IMinerClientService)));
            _serviceHosts = new List <ServiceHost>
            {
                minerClientServiceHost
            };
            foreach (var serviceHost in _serviceHosts)
            {
                ServiceMetadataBehavior serviceMetadata = serviceHost.Description.Behaviors.Find <ServiceMetadataBehavior>();
                if (serviceMetadata == null)
                {
                    serviceMetadata = new ServiceMetadataBehavior();
                    serviceHost.Description.Behaviors.Add(serviceMetadata);
                }
                serviceMetadata.HttpGetEnabled = false;

                serviceHost.Open();
            }

            Global.Logger.OkDebugLine($"服务启动成功: {DateTime.Now}.");
            Global.Logger.InfoDebugLine("服务列表:");
            foreach (var serviceHost in _serviceHosts)
            {
                foreach (var endpoint in serviceHost.Description.Endpoints)
                {
                    Global.Logger.InfoDebugLine(endpoint.Address.Uri.ToString());
                }
            }
            Global.Logger.OkDebugLine("Wcf服务启动完成");

            Server.TimeService.GetTime((remoteTime) => {
                if (Math.Abs((DateTime.Now - remoteTime).TotalSeconds) < Global.DesyncSeconds)
                {
                    Global.Logger.OkDebugLine("时间同步");
                }
                else
                {
                    Global.Logger.WarnDebugLine($"本机时间和服务器时间不同步,请调整,本地:{DateTime.Now},服务器:{remoteTime}");
                }
            });

            Windows.Registry.SetValue(Registry.Users, ClientId.NTMinerRegistrySubKey, "Location", ClientId.AppFileFullName);
            Windows.Registry.SetValue(Registry.Users, ClientId.NTMinerRegistrySubKey, "Arguments", string.Join(" ", CommandLineArgs.Args));
            Windows.Registry.SetValue(Registry.Users, ClientId.NTMinerRegistrySubKey, "CurrentVersion", CurrentVersion.ToString());
            Windows.Registry.SetValue(Registry.Users, ClientId.NTMinerRegistrySubKey, "CurrentVersionTag", CurrentVersionTag);

            Report.Init(this);

            int      shareCount = 0;
            DateTime shareOn    = DateTime.Now;

            #region 挖矿开始时将无份额内核重启份额计数置0
            Global.Access <MineStartedEvent>(
                Guid.Parse("e69e8729-868b-4b5d-b120-2914fffddf90"),
                "挖矿开始时将无份额内核重启份额计数置0",
                LogEnum.None,
                action: message => {
                shareCount = 0;
                shareOn    = DateTime.Now;
            });
            #endregion
            #region 每10秒钟检查是否需要重启
            Global.Access <Per10SecondEvent>(
                Guid.Parse("16b3b7b4-5e6c-46b0-97a4-90e085614b78"),
                "每10秒钟检查是否需要重启",
                LogEnum.None,
                action: message => {
                #region 重启电脑
                try {
                    if (MinerProfile.IsPeriodicRestartComputer)
                    {
                        if ((DateTime.Now - this.CreatedOn).TotalHours > MinerProfile.PeriodicRestartComputerHours)
                        {
                            Global.Logger.WarnWriteLine($"每运行{MinerProfile.PeriodicRestartKernelHours}小时重启电脑");
                            Windows.Power.Restart();
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Global.Logger.ErrorDebugLine(e.Message, e);
                }
                #endregion

                #region 周期重启内核
                try {
                    if (IsMining && MinerProfile.IsPeriodicRestartKernel)
                    {
                        if ((DateTime.Now - CurrentMineContext.CreatedOn).TotalHours > MinerProfile.PeriodicRestartKernelHours)
                        {
                            Global.Logger.WarnWriteLine($"每运行{MinerProfile.PeriodicRestartKernelHours}小时重启内核");
                            RestartMine();
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Global.Logger.ErrorDebugLine(e.Message, e);
                }
                #endregion

                #region 收益没有增加重启内核
                try {
                    if (IsMining && MinerProfile.IsNoShareRestartKernel)
                    {
                        if ((DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartKernelMinutes)
                        {
                            if (this.CurrentMineContext.MainCoin != null)
                            {
                                ICoinShare mainCoinShare = this.CoinShareSet.GetOrCreate(this.CurrentMineContext.MainCoin.GetId());
                                int totalShare           = mainCoinShare.TotalShareCount;
                                if ((this.CurrentMineContext is IDualMineContext dualMineContext) && dualMineContext.DualCoin != null)
                                {
                                    ICoinShare dualCoinShare = this.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                                    totalShare += dualCoinShare.TotalShareCount;
                                }
                                if (shareCount == totalShare)
                                {
                                    Global.Logger.WarnWriteLine($"{MinerProfile.NoShareRestartKernelMinutes}分钟收益没有增加重启内核");
                                    RestartMine();
                                }
                                else
                                {
                                    shareCount = totalShare;
                                    shareOn    = DateTime.Now;
                                }
                            }