Example #1
0
 public void Init(Action callback)
 {
     Task.Factory.StartNew(() => {
         bool isWork = Environment.GetCommandLineArgs().Contains("--work", StringComparer.OrdinalIgnoreCase);
         if (isWork)
         {
             DoInit(isWork, callback);
             if (IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(true);
             }
             return;
         }
         else
         {
             if (IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(false);
             }
         }
         // 如果是Debug模式且不是群控客户端且不是作业则使用本地数据库初始化
         if (DevMode.IsDebugMode && !VirtualRoot.IsMinerStudio)
         {
             DoInit(isWork: false, callback: callback);
             return;
         }
         Logger.InfoDebugLine("开始下载server.json");
         SpecialPath.GetAliyunServerJson((data) => {
             // 如果server.json未下载成功则不覆写本地server.json
             if (data != null && data.Length != 0)
             {
                 Logger.InfoDebugLine("GetAliyunServerJson下载成功");
                 var serverJson = Encoding.UTF8.GetString(data);
                 if (!string.IsNullOrEmpty(serverJson))
                 {
                     SpecialPath.WriteServerJsonFile(serverJson);
                 }
                 OfficialServer.GetJsonFileVersionAsync(AssemblyInfo.ServerJsonFileName, (serverJsonFileVersion, minerClientVersion) => {
                     SetServerJsonVersion(serverJsonFileVersion);
                     AppVersionChangedEvent.PublishIfNewVersion(minerClientVersion);
                 });
             }
             else
             {
                 Logger.InfoDebugLine("GetAliyunServerJson下载失败");
             }
             DoInit(isWork, callback);
         });
         #region 发生了用户活动时检查serverJson是否有新版本
         VirtualRoot.On <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                          action: message => {
             OfficialServer.GetJsonFileVersionAsync(AssemblyInfo.ServerJsonFileName, (serverJsonFileVersion, minerClientVersion) => {
                 AppVersionChangedEvent.PublishIfNewVersion(minerClientVersion);
                 string localServerJsonFileVersion = GetServerJsonVersion();
                 if (!string.IsNullOrEmpty(serverJsonFileVersion) && localServerJsonFileVersion != serverJsonFileVersion)
                 {
                     SpecialPath.GetAliyunServerJson((data) => {
                         Write.UserInfo($"server.json配置文件有新版本{localServerJsonFileVersion}->{serverJsonFileVersion}");
                         string rawJson = Encoding.UTF8.GetString(data);
                         SpecialPath.WriteServerJsonFile(rawJson);
                         SetServerJsonVersion(serverJsonFileVersion);
                         ReInitServerJson();
                         bool isUseJson = !DevMode.IsDebugMode || VirtualRoot.IsMinerStudio;
                         if (isUseJson)
                         {
                             // 作业模式下界面是禁用的,所以这里的初始化isWork必然是false
                             ContextReInit(isWork: VirtualRoot.IsMinerStudio);
                             Write.UserInfo("刷新完成");
                         }
                         else
                         {
                             Write.UserInfo("不是使用的server.json,无需刷新");
                         }
                     });
                 }
                 else
                 {
                     Write.DevDebug("server.json没有新版本");
                 }
             });
         });
         #endregion
     });
     // 因为这个操作大概需要200毫秒
     Task.Factory.StartNew(() => {
         NVIDIAGpuSet.NvmlInit();
     });
 }
Example #2
0
        static void Main()
        {
            NTMinerConsole.SetIsMainUiOk(true);
            NTMinerConsole.DisbleQuickEditMode();
            try {
                bool mutexCreated;
                try {
                    // 锁名称上带上本节点的端口号,从而允许一个服务器上运行多个WebApiServer节点,这在软升级服务端程序时有用。
                    // 升级WebApiServer程序的时候步骤是:
                    // 1,在另一个端口启动新版本的程序;
                    // 2,让Widnows将来自旧端口的所有tcp请求转发到新端口;
                    // 3,退出旧版本的程序并更新到新版本;
                    // 4,删除第2步添加的Windows的端口转发;
                    // 5,退出第1步运行的节点;
                    // TODO:实现软升级策略
                    _sMutexApp = new Mutex(true, $"NTMinerServicesMutex{ServerRoot.HostConfig.GetServerPort().ToString()}", out mutexCreated);
                }
                catch {
                    mutexCreated = false;
                }
                if (mutexCreated)
                {
                    try {
                        // 用本节点的地址作为队列名,消费消息时根据路由键区分消息类型
                        string queue        = $"{ServerAppType.WebApiServer.GetName()}.{ServerRoot.HostConfig.ThisServerAddress}";
                        string durableQueue = queue + MqKeyword.DurableQueueEndsWith;
                        AbstractMqMessagePath[] mqMessagePaths = new AbstractMqMessagePath[] {
                            new UserMqMessagePath(durableQueue),
                            new MinerClientMqMessagePath(queue)
                        };
                        if (!ServerConnection.Create(ServerAppType.WebApiServer, mqMessagePaths, out IServerConnection serverConfig))
                        {
                            NTMinerConsole.UserError("启动失败,无法继续,因为服务器上下文创建失败");
                            return;
                        }
                        Console.Title = $"{ServerAppType.WebApiServer.GetName()}_{ServerRoot.HostConfig.ThisServerAddress}";
                        OssClient     = new OssClient(ServerRoot.HostConfig.OssEndpoint, ServerRoot.HostConfig.OssAccessKeyId, ServerRoot.HostConfig.OssAccessKeySecret);
                        var minerClientMqSender = new MinerClientMqSender(serverConfig);
                        var userMqSender        = new UserMqSender(serverConfig);

                        var minerRedis     = new MinerRedis(serverConfig);
                        var speedDataRedis = new SpeedDataRedis(serverConfig);
                        var userRedis      = new UserRedis(serverConfig);
                        var captchaRedis   = new CaptchaRedis(serverConfig);

                        WsServerNodeRedis      = new WsServerNodeRedis(serverConfig);
                        WsServerNodeAddressSet = new WsServerNodeAddressSet(WsServerNodeRedis);
                        UserSet           = new UserSet(userRedis, userMqSender);
                        UserAppSettingSet = new UserAppSettingSet();
                        CaptchaSet        = new CaptchaSet(captchaRedis);
                        CalcConfigSet     = new CalcConfigSet();
                        NTMinerWalletSet  = new NTMinerWalletSet();
                        GpuNameSet        = new GpuNameSet();
                        ClientDataSet clientDataSet = new ClientDataSet(minerRedis, speedDataRedis, minerClientMqSender);
                        ClientDataSet          = clientDataSet;
                        CoinSnapshotSet        = new CoinSnapshotSet(clientDataSet);
                        MineWorkSet            = new UserMineWorkSet();
                        MinerGroupSet          = new UserMinerGroupSet();
                        NTMinerFileSet         = new NTMinerFileSet();
                        OverClockDataSet       = new OverClockDataSet();
                        KernelOutputKeywordSet = new KernelOutputKeywordSet(SpecialPath.LocalDbFileFullName, isServer: true);
                        ServerMessageSet       = new ServerMessageSet(SpecialPath.LocalDbFileFullName, isServer: true);
                        UpdateServerMessageTimestamp();
                        if (VirtualRoot.LocalAppSettingSet.TryGetAppSetting(nameof(KernelOutputKeywordTimestamp), out IAppSetting appSetting) && appSetting.Value is DateTime value)
                        {
                            KernelOutputKeywordTimestamp = value;
                        }
                        else
                        {
                            KernelOutputKeywordTimestamp = Timestamp.UnixBaseTime;
                        }
                    }
                    catch (Exception e) {
                        NTMinerConsole.UserError(e.Message);
                        NTMinerConsole.UserError(e.StackTrace);
                        NTMinerConsole.UserInfo("按任意键退出");
                        Console.ReadKey();
                        return;
                    }
                    VirtualRoot.StartTimer();
                    NTMinerRegistry.SetAutoBoot("NTMinerServices", true);
                    Type thisType = typeof(WebApiRoot);
                    Run();
                }
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
            }
        }
Example #3
0
        public static SpeedData CreateSpeedData()
        {
            INTMinerRoot root = NTMinerRoot.Instance;
            SpeedData    data = new SpeedData {
                KernelSelfRestartCount = 0,
                IsAutoBoot             = NTMinerRegistry.GetIsAutoBoot(),
                IsAutoStart            = NTMinerRegistry.GetIsAutoStart(),
                Version       = NTMinerRoot.CurrentVersion.ToString(4),
                BootOn        = root.CreatedOn,
                MineStartedOn = null,
                IsMining      = root.IsMining,
                MineWorkId    = root.MinerProfile.MineWork != null?root.MinerProfile.MineWork.GetId() : Guid.Empty,
                                    MinerName           = root.MinerProfile.MinerName,
                                    GpuInfo             = root.GpuSetInfo,
                                    ClientId            = VirtualRoot.Id,
                                    MainCoinCode        = string.Empty,
                                    MainCoinWallet      = string.Empty,
                                    MainCoinTotalShare  = 0,
                                    MainCoinRejectShare = 0,
                                    MainCoinSpeed       = 0,
                                    DualCoinCode        = string.Empty,
                                    DualCoinTotalShare  = 0,
                                    DualCoinRejectShare = 0,
                                    DualCoinSpeed       = 0,
                                    DualCoinPool        = string.Empty,
                                    DualCoinWallet      = string.Empty,
                                    IsDualCoinEnabled   = false,
                                    Kernel                        = string.Empty,
                                    MainCoinPool                  = string.Empty,
                                    OSName                        = Windows.OS.Instance.WindowsEdition,
                                    GpuDriver                     = root.GpuSet.DriverVersion,
                                    GpuType                       = root.GpuSet.GpuType,
                                    OSVirtualMemoryMb             = NTMinerRoot.OSVirtualMemoryMb,
                                    KernelCommandLine             = NTMinerRoot.UserKernelCommandLine,
                                    DiskSpace                     = NTMinerRoot.DiskSpace,
                                    IsAutoRestartKernel           = root.MinerProfile.IsAutoRestartKernel,
                                    IsNoShareRestartKernel        = root.MinerProfile.IsNoShareRestartKernel,
                                    IsNoShareRestartComputer      = root.MinerProfile.IsNoShareRestartComputer,
                                    NoShareRestartComputerMinutes = root.MinerProfile.NoShareRestartComputerMinutes,
                                    IsPeriodicRestartComputer     = root.MinerProfile.IsPeriodicRestartComputer,
                                    IsPeriodicRestartKernel       = root.MinerProfile.IsPeriodicRestartKernel,
                                    NoShareRestartKernelMinutes   = root.MinerProfile.NoShareRestartKernelMinutes,
                                    PeriodicRestartComputerHours  = root.MinerProfile.PeriodicRestartComputerHours,
                                    PeriodicRestartKernelHours    = root.MinerProfile.PeriodicRestartKernelHours,
                                    GpuTable                      = root.GpusSpeed.Where(a => a.Gpu.Index != NTMinerRoot.GpuAllId).Select(a => new GpuSpeedData {
                    Index            = a.Gpu.Index,
                    Name             = a.Gpu.Name,
                    TotalMemory      = a.Gpu.TotalMemory,
                    MainCoinSpeed    = a.MainCoinSpeed.Value,
                    DualCoinSpeed    = a.DualCoinSpeed.Value,
                    AcceptShare      = a.MainCoinSpeed.AcceptShare,
                    FoundShare       = a.MainCoinSpeed.FoundShare,
                    RejectShare      = a.MainCoinSpeed.RejectShare,
                    FanSpeed         = a.Gpu.FanSpeed,
                    Temperature      = a.Gpu.Temperature,
                    PowerUsage       = a.Gpu.PowerUsage,
                    Cool             = a.Gpu.Cool,
                    PowerCapacity    = a.Gpu.PowerCapacity,
                    CoreClockDelta   = a.Gpu.CoreClockDelta,
                    MemoryClockDelta = a.Gpu.MemoryClockDelta,
                    TempLimit        = a.Gpu.TempLimit,
                    CoreVoltage      = a.Gpu.CoreVoltage,
                    MemoryVoltage    = a.Gpu.MemoryVoltage
                }).ToArray()
            };

            #region 当前选中的币种是什么
            if (root.CoinSet.TryGetCoin(root.MinerProfile.CoinId, out ICoin mainCoin))
            {
                data.MainCoinCode = mainCoin.Code;
                ICoinProfile coinProfile = root.MinerProfile.GetCoinProfile(mainCoin.GetId());
                data.MainCoinWallet = coinProfile.Wallet;
                if (root.PoolSet.TryGetPool(coinProfile.PoolId, out IPool mainCoinPool))
                {
                    data.MainCoinPool = mainCoinPool.Server;
                    if (mainCoinPool.IsUserMode)
                    {
                        IPoolProfile mainCoinPoolProfile = root.MinerProfile.GetPoolProfile(coinProfile.PoolId);
                        data.MainCoinWallet = mainCoinPoolProfile.UserName;
                    }
                }
                else
                {
                    data.MainCoinPool = string.Empty;
                }
                if (root.CoinKernelSet.TryGetCoinKernel(coinProfile.CoinKernelId, out ICoinKernel coinKernel))
                {
                    if (root.KernelSet.TryGetKernel(coinKernel.KernelId, out IKernel kernel))
                    {
                        data.Kernel = kernel.GetFullName();
                        ICoinKernelProfile coinKernelProfile = root.MinerProfile.GetCoinKernelProfile(coinProfile.CoinKernelId);
                        data.IsDualCoinEnabled = coinKernelProfile.IsDualCoinEnabled;
                        if (coinKernelProfile.IsDualCoinEnabled)
                        {
                            if (root.CoinSet.TryGetCoin(coinKernelProfile.DualCoinId, out ICoin dualCoin))
                            {
                                data.DualCoinCode = dualCoin.Code;
                                ICoinProfile dualCoinProfile = root.MinerProfile.GetCoinProfile(dualCoin.GetId());
                                data.DualCoinWallet = dualCoinProfile.DualCoinWallet;
                                if (root.PoolSet.TryGetPool(dualCoinProfile.DualCoinPoolId, out IPool dualCoinPool))
                                {
                                    data.DualCoinPool = dualCoinPool.Server;
                                    if (dualCoinPool.IsUserMode)
                                    {
                                        IPoolProfile dualCoinPoolProfile = root.MinerProfile.GetPoolProfile(dualCoinProfile.DualCoinPoolId);
                                        data.DualCoinWallet = dualCoinPoolProfile.UserName;
                                    }
                                }
                                else
                                {
                                    data.DualCoinPool = string.Empty;
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            if (root.IsMining)
            {
                var mineContext = root.CurrentMineContext;
                if (mineContext != null)
                {
                    data.KernelSelfRestartCount = mineContext.KernelSelfRestartCount;
                    data.MineStartedOn          = mineContext.CreatedOn;
                    data.KernelCommandLine      = mineContext.CommandLine;
                }
                // 判断上次报告的算力币种和本次报告的是否相同,否则说明刚刚切换了币种默认第一次报告0算力
                if (_sLastSpeedMainCoin == null || _sLastSpeedMainCoin == root.CurrentMineContext.MainCoin)
                {
                    _sLastSpeedMainCoin = root.CurrentMineContext.MainCoin;
                    Guid       coinId     = root.CurrentMineContext.MainCoin.GetId();
                    IGpusSpeed gpuSpeeds  = NTMinerRoot.Instance.GpusSpeed;
                    IGpuSpeed  totalSpeed = gpuSpeeds.CurrentSpeed(NTMinerRoot.GpuAllId);
                    data.MainCoinSpeed = totalSpeed.MainCoinSpeed.Value;
                    ICoinShare share = root.CoinShareSet.GetOrCreate(coinId);
                    data.MainCoinTotalShare  = share.TotalShareCount;
                    data.MainCoinRejectShare = share.RejectShareCount;
                }
                else
                {
                    _sLastSpeedMainCoin = root.CurrentMineContext.MainCoin;
                }
                if (root.CurrentMineContext is IDualMineContext dualMineContext)
                {
                    // 判断上次报告的算力币种和本次报告的是否相同,否则说明刚刚切换了币种默认第一次报告0算力
                    if (_sLastSpeedDualCoin == null || _sLastSpeedDualCoin == dualMineContext.DualCoin)
                    {
                        _sLastSpeedDualCoin = dualMineContext.DualCoin;
                        Guid       coinId     = dualMineContext.DualCoin.GetId();
                        IGpusSpeed gpuSpeeds  = NTMinerRoot.Instance.GpusSpeed;
                        IGpuSpeed  totalSpeed = gpuSpeeds.CurrentSpeed(NTMinerRoot.GpuAllId);
                        data.DualCoinSpeed = totalSpeed.DualCoinSpeed.Value;
                        ICoinShare share = root.CoinShareSet.GetOrCreate(coinId);
                        data.DualCoinTotalShare  = share.TotalShareCount;
                        data.DualCoinRejectShare = share.RejectShareCount;
                    }
                    else
                    {
                        _sLastSpeedDualCoin = dualMineContext.DualCoin;
                    }
                }
            }
            return(data);
        }
Example #4
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            VirtualRoot.BuildCmdPath <ShowFileDownloaderCommand>(action: message => {
                UIThread.Execute(() => {
                    FileDownloader.ShowWindow(message.DownloadFileUrl, message.FileTitle, message.DownloadComplete);
                });
            });
            VirtualRoot.BuildCmdPath <UpgradeCommand>(action: message => {
                AppStatic.Upgrade(message.FileName, message.Callback);
            });
            try {
                appMutex = new Mutex(true, s_appPipName, out createdNew);
            }
            catch (Exception) {
                createdNew = false;
            }

            if (createdNew)
            {
                this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                NotiCenterWindow.ShowWindow();
                LoginWindow.Login(() => {
                    bool isInnerIp = Net.Util.IsInnerIp(NTMinerRegistry.GetControlCenterHost());
                    if (isInnerIp)
                    {
                        NTMinerServices.NTMinerServicesUtil.RunNTMinerServices(() => {
                            Init();
                        });
                    }
                    else
                    {
                        Init();
                    }
                });
                VirtualRoot.BuildCmdPath <CloseNTMinerCommand>(action: message => {
                    // 不能推迟这个日志记录的时机,因为推迟会有windows异常日志
                    VirtualRoot.ThisLocalWarn(nameof(NTMinerRoot), $"退出{VirtualRoot.AppName}。原因:{message.Reason}");
                    UIThread.Execute(() => {
                        try {
                            Shutdown();
                        }
                        catch (Exception ex) {
                            Logger.ErrorDebugLine(ex);
                            Environment.Exit(0);
                        }
                    });
                });
            }
            else
            {
                try {
                    _appViewFactory.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerStudio);
                }
                catch (Exception) {
                    DialogWindow.ShowSoftDialog(new DialogWindowViewModel(
                                                    message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。",
                                                    title: "alert",
                                                    icon: "Icon_Error"));
                    Process currentProcess = Process.GetCurrentProcess();
                    NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
                }
            }
            base.OnStartup(e);
        }
Example #5
0
        static void Main()
        {
            VirtualRoot.SetOut(new ConsoleOut());
            NTMinerConsole.MainUiOk();
            NTMinerConsole.DisbleQuickEditMode();
            DevMode.SetDevMode();

            Windows.ConsoleHandler.Register(Exit);

            try {
                bool mutexCreated;
                try {
                    // 锁名称上带上本节点的端口号,从而允许一个服务器上运行多个WebApiServer节点,这在软升级服务端程序时有用。
                    // 升级WebApiServer程序的时候步骤是:
                    // 1,在另一个端口启动新版本的程序;
                    // 2,让Widnows将来自旧端口的所有tcp请求转发到新端口;
                    // 3,退出旧版本的程序并更新到新版本;
                    // 4,删除第2步添加的Windows的端口转发;
                    // 5,退出第1步运行的节点;
                    // TODO:实现软升级策略
                    _sMutexApp = new Mutex(true, $"NTMinerServicesMutex{ServerRoot.HostConfig.GetServerPort().ToString()}", out mutexCreated);
                }
                catch {
                    mutexCreated = false;
                }
                if (mutexCreated)
                {
                    try {
                        // 用本节点的地址作为队列名,消费消息时根据路由键区分消息类型
                        string queue         = $"{nameof(ServerAppType.WebApiServer)}.{ServerRoot.HostConfig.ThisServerAddress}";
                        string durableQueue  = queue + MqKeyword.DurableQueueEndsWith;
                        string wsBreathQueue = queue + MqKeyword.WsBreathQueueEndsWith;
                        AbstractMqMessagePath[] mqMessagePaths = new AbstractMqMessagePath[] {
                            new UserMqMessagePath(durableQueue),
                            new CalcConfigMqMessagePath(queue),
                            new MinerClientMqMessagePath(queue),
                            new WsBreathMqMessagePath(wsBreathQueue),
                            new OperationMqMessagePath(queue),
                            new MqCountMqMessagePath(queue),
                            new ClientTestIdMqMessagePath(queue)
                        };
                        if (!MqRedis.Create(ServerAppType.WebApiServer, mqMessagePaths, out IMqRedis mqRedis))
                        {
                            NTMinerConsole.UserError("启动失败,无法继续,因为服务器上下文创建失败");
                            return;
                        }
                        Console.Title = $"{nameof(ServerAppType.WebApiServer)}_{ServerRoot.HostConfig.ThisServerAddress}";
                        // 阿里云OSS坑爹比七牛Kodo贵一半
                        CloudFileUrlGenerater = new AliCloudOSSFileUrlGenerater();
                        IRedis redis = mqRedis;
                        IMq    mq    = mqRedis;
                        AdminMqSender         = new AdminMqSender(mq);
                        ClientTestIdDataRedis = new ClientTestIdDataRedis(redis);
                        var minerClientMqSender = new MinerClientMqSender(mq);
                        var userMqSender        = new UserMqSender(mq);
                        var calcConfigMqSender  = new CalcConfigMqSender(mq);

                        var minerRedis          = new MinerDataRedis(redis);
                        var clientActiveOnRedis = new ClientActiveOnRedis(redis);
                        var speedDataRedis      = new SpeedDataRedis(redis);
                        var userRedis           = new UserDataRedis(redis);
                        var captchaRedis        = new CaptchaDataRedis(redis);
                        var calcConfigRedis     = new CalcConfigDataRedis(redis);

                        MqCountSet             = new MqCountSet();
                        WsServerNodeRedis      = new WsServerNodeRedis(redis);
                        WsServerNodeAddressSet = new WsServerNodeAddressSet(WsServerNodeRedis);
                        UserSet           = new UserSet(userRedis, userMqSender);
                        UserAppSettingSet = new UserAppSettingSet();
                        CaptchaSet        = new CaptchaSet(captchaRedis);
                        CalcConfigSet     = new CalcConfigSet(calcConfigRedis, calcConfigMqSender);
                        NTMinerWalletSet  = new NTMinerWalletSet();
                        GpuNameSet        = new GpuNameSet();
                        ClientDataSet clientDataSet = new ClientDataSet(minerRedis, clientActiveOnRedis, speedDataRedis, minerClientMqSender);
                        ClientDataSet = clientDataSet;
                        var operationMqSender = new OperationMqSender(mq);
                        MineWorkSet            = new UserMineWorkSet(operationMqSender);
                        MinerGroupSet          = new UserMinerGroupSet();
                        NTMinerFileSet         = new NTMinerFileSet();
                        OverClockDataSet       = new OverClockDataSet();
                        KernelOutputKeywordSet = new KernelOutputKeywordSet(SpecialPath.LocalDbFileFullName);
                        ServerMessageSet       = new ServerMessageSet(SpecialPath.LocalDbFileFullName);
                        if (VirtualRoot.LocalAppSettingSet.TryGetAppSetting(nameof(KernelOutputKeywordTimestamp), out IAppSetting appSetting) && appSetting.Value is DateTime value)
                        {
                            KernelOutputKeywordTimestamp = value;
                        }
                        else
                        {
                            KernelOutputKeywordTimestamp = Timestamp.UnixBaseTime;
                        }
                    }
                    catch (Exception e) {
                        NTMinerConsole.UserError(e.Message);
                        NTMinerConsole.UserError(e.StackTrace);
                        NTMinerConsole.UserInfo("按任意键退出");
                        Console.ReadKey();
                        return;
                    }
                    VirtualRoot.StartTimer();
                    NTMinerRegistry.SetAutoBoot("NTMinerServices", true);
                    Type thisType = typeof(AppRoot);
                    Run();
                }
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
            }
        }
Example #6
0
        private void Link()
        {
            VirtualRoot.AddCmdPath <RegCmdHereCommand>(action: message => {
                try {
                    Windows.Cmd.RegCmdHere();
                    VirtualRoot.ThisLocalInfo(nameof(NTMinerContext), "添加windows右键命令行成功");
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                    VirtualRoot.ThisLocalError(nameof(NTMinerContext), "添加windows右键命令行失败", OutEnum.Warn);
                }
            }, location: this.GetType());
            VirtualRoot.AddCmdPath <UnRegCmdHereCommand>(action: message => {
                try {
                    Windows.Cmd.UnRegCmdHere();
                    VirtualRoot.ThisLocalInfo(nameof(NTMinerContext), "移除windows右键命令行成功");
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                    VirtualRoot.ThisLocalError(nameof(NTMinerContext), "移除windows右键命令行失败", OutEnum.Warn);
                }
            }, location: this.GetType());
            VirtualRoot.AddEventPath <Per1MinuteEvent>("每1分钟阻止系统休眠", LogEnum.None,
                                                       action: message => {
                Power.PreventSleep();
            }, location: this.GetType());
            #region 挖矿开始时将无份额内核重启份额计数置0
            int      shareCount   = 0;
            DateTime shareOn      = DateTime.Now;
            DateTime hightSpeedOn = DateTime.Now;
            VirtualRoot.AddEventPath <MineStartedEvent>("挖矿开始后将无份额内核重启份额计数置0", LogEnum.DevConsole,
                                                        action: message => {
                // 将无份额内核重启份额计数置0
                shareCount   = 0;
                hightSpeedOn = DateTime.Now;
                if (!message.MineContext.IsRestart)
                {
                    // 当不是内核重启时更新shareOn,如果是内核重启不用更新shareOn从而给不干扰无内核矿机重启的逻辑
                    shareOn = DateTime.Now;
                }
            }, location: this.GetType());
            #endregion
            #region 每20秒钟检查是否需要重启
            VirtualRoot.AddEventPath <Per20SecondEvent>("每20秒钟检查是否需要重启", LogEnum.None,
                                                        action: message => {
                #region 低算力重启电脑
                if (IsMining && LockedMineContext.ProcessCreatedOn != DateTime.MinValue)
                {
                    var coinProfile = MinerProfile.GetCoinProfile(MinerProfile.CoinId);
                    if (coinProfile.IsLowSpeedRestartComputer && coinProfile.LowSpeed != 0 && coinProfile.LowSpeedRestartComputerMinutes > 0)
                    {
                        IGpuSpeed totalSpeed = GpusSpeed.CurrentSpeed(GpuAllId);
                        if (totalSpeed.MainCoinSpeed.SpeedOn.AddMinutes(coinProfile.LowSpeedRestartComputerMinutes) >= message.BornOn)
                        {
                            if (totalSpeed.MainCoinSpeed.Value.ToNearSpeed(coinProfile.LowSpeed) >= coinProfile.LowSpeed)
                            {
                                hightSpeedOn = message.BornOn;
                            }
                        }
                        if (hightSpeedOn.AddMinutes(coinProfile.LowSpeedRestartComputerMinutes) < message.BornOn)
                        {
                            string coinCode = string.Empty;
                            if (ServerContext.CoinSet.TryGetCoin(MinerProfile.CoinId, out ICoin coin))
                            {
                                coinCode = coin.Code;
                            }
                            VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), $"{coinCode}总算力持续{coinProfile.LowSpeedRestartComputerMinutes}分钟低于{coinProfile.LowSpeed}重启电脑", toConsole: true);
                            VirtualRoot.Execute(new ShowRestartWindowsCommand(countDownSeconds: 10));
                            if (!MinerProfile.IsAutoBoot || !NTMinerRegistry.GetIsAutoStart())
                            {
                                VirtualRoot.Execute(new SetAutoStartCommand(true, true));
                            }
                            return;
                        }
                    }
                    else
                    {
                        hightSpeedOn = message.BornOn;
                    }
                }
                #endregion

                #region 周期重启电脑
                try {
                    if (MinerProfile.IsPeriodicRestartComputer)
                    {
                        if ((DateTime.Now - this.CreatedOn).TotalMinutes > 60 * MinerProfile.PeriodicRestartComputerHours + MinerProfile.PeriodicRestartComputerMinutes)
                        {
                            string content = $"每运行{MinerProfile.PeriodicRestartKernelHours.ToString()}小时{MinerProfile.PeriodicRestartComputerMinutes.ToString()}分钟重启电脑";
                            VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), content, toConsole: true);
                            VirtualRoot.Execute(new ShowRestartWindowsCommand(countDownSeconds: 10));
                            if (!MinerProfile.IsAutoBoot || !NTMinerRegistry.GetIsAutoStart())
                            {
                                VirtualRoot.Execute(new SetAutoStartCommand(true, true));
                            }
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion

                #region 周期重启内核
                try {
                    if (IsMining && MinerProfile.IsPeriodicRestartKernel && LockedMineContext.MineStartedOn != DateTime.MinValue)
                    {
                        if ((DateTime.Now - LockedMineContext.MineStartedOn).TotalMinutes > 60 * MinerProfile.PeriodicRestartKernelHours + MinerProfile.PeriodicRestartKernelMinutes)
                        {
                            VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), $"每运行{MinerProfile.PeriodicRestartKernelHours.ToString()}小时{MinerProfile.PeriodicRestartKernelMinutes.ToString()}分钟重启内核", toConsole: true);
                            RestartMine();
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion

                #region 无份额重启内核
                try {
                    if (IsMining && this.LockedMineContext.MainCoin != null)
                    {
                        int totalShare       = 0;
                        bool restartComputer = MinerProfile.NoShareRestartComputerMinutes > 0 && MinerProfile.IsNoShareRestartComputer && (DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartComputerMinutes;
                        bool restartKernel   = MinerProfile.NoShareRestartKernelMinutes > 0 && MinerProfile.IsNoShareRestartKernel && (DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartKernelMinutes;
                        if (restartComputer || restartKernel)
                        {
                            ICoinShare mainCoinShare = this.CoinShareSet.GetOrCreate(this.LockedMineContext.MainCoin.GetId());
                            totalShare = mainCoinShare.TotalShareCount;
                            if ((this.LockedMineContext is IDualMineContext dualMineContext) && dualMineContext.DualCoin != null)
                            {
                                ICoinShare dualCoinShare = this.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                                totalShare += dualCoinShare.TotalShareCount;
                            }
                            // 如果份额没有增加
                            if (shareCount == totalShare)
                            {
                                bool isMineStartedARestartComputerMinutes = (DateTime.Now - this.LockedMineContext.MineStartedOn).TotalMinutes > MinerProfile.NoShareRestartComputerMinutes;
                                if (restartComputer && isMineStartedARestartComputerMinutes)
                                {
                                    if (!MinerProfile.IsAutoBoot || !NTMinerRegistry.GetIsAutoStart())
                                    {
                                        VirtualRoot.Execute(new SetAutoStartCommand(true, true));
                                    }
                                    string content = $"{MinerProfile.NoShareRestartComputerMinutes.ToString()}分钟无份额重启电脑";
                                    VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), content, toConsole: true);
                                    VirtualRoot.Execute(new ShowRestartWindowsCommand(countDownSeconds: 10));
                                    return;    // 退出
                                }
                                bool isMineStartedARestartKernelMinutes = (DateTime.Now - this.LockedMineContext.MineStartedOn).TotalMinutes > MinerProfile.NoShareRestartKernelMinutes;
                                if (restartKernel && isMineStartedARestartKernelMinutes)
                                {
                                    VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), $"{MinerProfile.NoShareRestartKernelMinutes.ToString()}分钟无份额重启内核", toConsole: true);
                                    RestartMine();
                                    return;    // 退出
                                }
                            }
                            if (totalShare > shareCount)
                            {
                                shareCount = totalShare;
                                shareOn    = DateTime.Now;
                            }
                        }
Example #7
0
 private void Link()
 {
     VirtualRoot.BuildCmdPath <CloseNTMinerCommand>(action: message => {
         UIThread.Execute(() => {
             try {
                 Shutdown();
             }
             catch (Exception e) {
                 Logger.ErrorDebugLine(e);
                 Environment.Exit(0);
             }
         });
     });
     #region 周期确保守护进程在运行
     VirtualRoot.BuildEventPath <Per1MinuteEvent>("周期确保守护进程在运行", LogEnum.DevConsole,
                                                  action: message => {
         Daemon.DaemonUtil.RunNTMinerDaemon();
     });
     #endregion
     #region 开始和停止挖矿后
     VirtualRoot.BuildEventPath <MineStartedEvent>("启动1080ti小药丸、启动DevConsole? 更新挖矿按钮状态", LogEnum.DevConsole,
                                                   action: message => {
         AppContext.Instance.MinerProfileVm.IsMining       = true;
         StartStopMineButtonViewModel.Instance.BtnStopText = "正在挖矿";
         // 启动DevConsole
         if (NTMinerRoot.IsUseDevConsole)
         {
             var mineContext     = message.MineContext;
             string poolIp       = mineContext.MainCoinPool.GetIp();
             string consoleTitle = mineContext.MainCoinPool.Server;
             Daemon.DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
         }
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Start();
     });
     VirtualRoot.BuildEventPath <MineStopedEvent>("停止挖矿后停止1080ti小药丸 挖矿停止后更新界面挖矿状态", LogEnum.DevConsole,
                                                  action: message => {
         AppContext.Instance.MinerProfileVm.IsMining       = false;
         StartStopMineButtonViewModel.Instance.BtnStopText = "尚未开始";
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Stop();
     });
     #endregion
     #region 处理禁用win10系统更新
     VirtualRoot.BuildCmdPath <BlockWAUCommand>(action: message => {
         NTMiner.Windows.WindowsUtil.BlockWAU();
     });
     #endregion
     #region 优化windows
     VirtualRoot.BuildCmdPath <Win10OptimizeCommand>(action: message => {
         NTMiner.Windows.WindowsUtil.Win10Optimize();
     });
     #endregion
     #region 处理开启A卡计算模式
     VirtualRoot.BuildCmdPath <SwitchRadeonGpuCommand>(action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             SwitchRadeonGpuMode(message.On);
         }
     });
     #endregion
     #region 处理A卡驱动签名
     VirtualRoot.BuildCmdPath <AtikmdagPatcherCommand>(action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             AtikmdagPatcher.AtikmdagPatcherUtil.Run();
         }
     });
     #endregion
     #region 启用或禁用windows远程桌面
     VirtualRoot.BuildCmdPath <EnableWindowsRemoteDesktopCommand>(action: message => {
         if (NTMinerRegistry.GetIsRemoteDesktopEnabled())
         {
             return;
         }
         string msg = "确定启用Windows远程桌面吗?";
         DialogWindow.ShowDialog(new DialogWindowViewModel(
                                     message: msg,
                                     title: "确认",
                                     onYes: () => {
             Rdp.SetRdpEnabled(true);
             Firewall.AddRdpRule();
         }));
     });
     #endregion
     #region 启用或禁用windows开机自动登录
     VirtualRoot.BuildCmdPath <EnableOrDisableWindowsAutoLoginCommand>(action: message => {
         if (NTMiner.Windows.OS.Instance.IsAutoAdminLogon)
         {
             return;
         }
         NTMiner.Windows.Cmd.RunClose("control", "userpasswords2");
     });
     #endregion
 }
Example #8
0
        private void BuildPaths()
        {
            VirtualRoot.BuildCmdPath <MinerClientActionCommand>(path: message => {
                #region
                try {
                    switch (message.ActionType)
                    {
                    case MinerClientActionType.SwitchRadeonGpuOn:
                        VirtualRoot.Execute(new SwitchRadeonGpuCommand(on: true));
                        break;

                    case MinerClientActionType.SwitchRadeonGpuOff:
                        VirtualRoot.Execute(new SwitchRadeonGpuCommand(on: false));
                        break;

                    case MinerClientActionType.BlockWAU:
                        VirtualRoot.Execute(new BlockWAUCommand());
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion
            }, location: this.GetType());
            #region 处理显示主界面命令
            VirtualRoot.BuildCmdPath <ShowMainWindowCommand>(path: message => {
                UIThread.Execute(() => {
                    _appViewFactory.ShowMainWindow(message.IsToggle, out Window _);
                    // 使状态栏显示显示最新状态
                    if (NTMinerContext.Instance.IsMining)
                    {
                        var mainCoin = NTMinerContext.Instance.LockedMineContext.MainCoin;
                        if (mainCoin == null)
                        {
                            return;
                        }
                        var coinShare = NTMinerContext.Instance.CoinShareSet.GetOrCreate(mainCoin.GetId());
                        VirtualRoot.RaiseEvent(new ShareChangedEvent(PathId.Empty, coinShare));
                        if ((NTMinerContext.Instance.LockedMineContext is IDualMineContext dualMineContext) && dualMineContext.DualCoin != null)
                        {
                            coinShare = NTMinerContext.Instance.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                            VirtualRoot.RaiseEvent(new ShareChangedEvent(PathId.Empty, coinShare));
                        }
                        AppRoot.GpuSpeedVms.Refresh();
                    }
                });
            }, location: this.GetType());
            #endregion
            #region 周期确保守护进程在运行
            VirtualRoot.BuildEventPath <Per1MinuteEvent>("周期确保守护进程在运行", LogEnum.DevConsole,
                                                         path: message => {
                Daemon.DaemonUtil.RunNTMinerDaemon();
                NoDevFee.NoDevFeeUtil.RunNTMinerNoDevFee();
            }, location: this.GetType());
            #endregion
            #region 开始和停止挖矿后
            VirtualRoot.BuildEventPath <StartingMineEvent>("开始挖矿时更新挖矿按钮状态", LogEnum.DevConsole,
                                                           path: message => {
                AppRoot.MinerProfileVm.IsMining = true;
                // 因为无界面模式不一定会构建挖矿状态按钮,所以放在这里而不放在挖矿按钮的VM中
                StartStopMineButtonViewModel.Instance.MineBtnText = "正在挖矿";
            }, location: this.GetType());
            VirtualRoot.BuildEventPath <MineStartedEvent>("启动1080ti小药丸、启动DevConsole? 更新挖矿按钮状态", LogEnum.DevConsole,
                                                          path: message => {
                // 启动DevConsole
                if (NTMinerContext.IsUseDevConsole)
                {
                    var mineContext     = message.MineContext;
                    string poolIp       = mineContext.MainCoinPool.GetIp();
                    string consoleTitle = mineContext.MainCoinPool.Server;
                    Daemon.DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
                }
                OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Start();
            }, location: this.GetType());
            VirtualRoot.BuildEventPath <MineStopedEvent>("停止挖矿后停止1080ti小药丸 挖矿停止后更新界面挖矿状态", LogEnum.DevConsole,
                                                         path: message => {
                AppRoot.MinerProfileVm.IsMining = false;
                // 因为无界面模式不一定会构建挖矿状态按钮,所以放在这里而不放在挖矿按钮的VM中
                StartStopMineButtonViewModel.Instance.MineBtnText = "尚未开始";
                OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Stop();
            }, location: this.GetType());
            #endregion
            #region 处理禁用win10系统更新
            VirtualRoot.BuildCmdPath <BlockWAUCommand>(path: message => {
                NTMiner.Windows.WindowsUtil.BlockWAU().ContinueWith(t => {
                    if (t.Exception == null)
                    {
                        VirtualRoot.ThisLocalInfo(nameof(App), "禁用windows系统更新成功", OutEnum.Success);
                    }
                    else
                    {
                        VirtualRoot.ThisLocalError(nameof(App), "禁用windows系统更新失败", OutEnum.Error);
                    }
                });
            }, location: this.GetType());
            #endregion
            #region 优化windows
            VirtualRoot.BuildCmdPath <Win10OptimizeCommand>(path: message => {
                NTMiner.Windows.WindowsUtil.Win10Optimize(e => {
                    if (e == null)
                    {
                        VirtualRoot.ThisLocalInfo(nameof(App), "优化Windows成功", OutEnum.Success);
                    }
                    else
                    {
                        VirtualRoot.ThisLocalError(nameof(App), "优化Windows失败", OutEnum.Error);
                    }
                });
            }, location: this.GetType());
            #endregion
            #region 处理开启A卡计算模式
            VirtualRoot.BuildCmdPath <SwitchRadeonGpuCommand>(path: message => {
                if (AdlHelper.IsHasATIGpu)
                {
                    AppRoot.SwitchRadeonGpu(message.On);
                }
            }, location: this.GetType());
            #endregion
            #region 处理A卡驱动签名
            VirtualRoot.BuildCmdPath <AtikmdagPatcherCommand>(path: message => {
                if (AdlHelper.IsHasATIGpu)
                {
                    AppRoot.OpenAtikmdagPatcher();
                }
            }, location: this.GetType());
            #endregion
            #region 启用或禁用windows远程桌面
            VirtualRoot.BuildCmdPath <EnableRemoteDesktopCommand>(path: message => {
                if (NTMinerRegistry.GetIsRdpEnabled())
                {
                    return;
                }
                string msg = "确定启用Windows远程桌面吗?";
                DialogWindow.ShowSoftDialog(new DialogWindowViewModel(
                                                message: msg,
                                                title: "确认",
                                                onYes: () => {
                    NTMinerRegistry.SetIsRdpEnabled(true);
                    Firewall.AddRdpRule();
                }));
            }, location: this.GetType());
            #endregion
            #region 启用或禁用windows开机自动登录
            VirtualRoot.BuildCmdPath <EnableOrDisableWindowsAutoLoginCommand>(path: message => {
                if (NTMiner.Windows.OS.Instance.IsAutoAdminLogon)
                {
                    return;
                }
                if (NTMiner.Windows.OS.Instance.IsGEWindows2004)
                {
                    WindowsAutoLogon.ShowWindow();
                }
                else
                {
                    VirtualRoot.Execute(new UnTopmostCommand());
                    NTMiner.Windows.Cmd.RunClose("control", "userpasswords2");
                }
            }, location: this.GetType());
            #endregion
        }
Example #9
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            if (!string.IsNullOrEmpty(CommandLineArgs.Upgrade))
            {
                AppStatic.Upgrade(CommandLineArgs.Upgrade, () => {
                    Environment.Exit(0);
                });
            }
            else
            {
                try {
                    appMutex = new Mutex(true, s_appPipName, out createdNew);
                }
                catch (Exception) {
                    createdNew = false;
                }
                if (createdNew)
                {
                    if (!NTMiner.Windows.WMI.IsWmiEnabled)
                    {
                        DialogWindow.ShowDialog(message: "开源矿工无法运行所需的组件,因为本机未开机WMI服务,开源矿工需要使用WMI服务检测windows的内存、显卡等信息,请先手动开启WMI。", title: "提醒", icon: "Icon_Error");
                        Shutdown();
                        Environment.Exit(0);
                    }
                    NTMinerOverClockUtil.ExtractResource();

                    AppStatic.SetIsMinerClient(true);
                    NotiCenterWindowViewModel.IsHotKeyEnabled = true;
                    SplashWindow splashWindow = new SplashWindow();
                    splashWindow.Show();
                    NotiCenterWindow.Instance.Show();
                    NTMinerRoot.Instance.Init(() => {
                        NTMinerRoot.KernelDownloader = new KernelDownloader();
                        UIThread.Execute(() => {
                            if (!NTMinerRegistry.GetIsNoUi() || !NTMinerRegistry.GetIsAutoStart())
                            {
                                Views.MainWindow.ShowMainWindow();
                            }
                            else
                            {
                                NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage("已切换为无界面模式运行", "开源矿工");
                            }
                            System.Drawing.Icon icon = new System.Drawing.Icon(GetResourceStream(new Uri("pack://application:,,,/NTMiner;component/logo.ico")).Stream);
                            AppHelper.NotifyIcon     = ExtendedNotifyIcon.Create(icon, "开源矿工", isMinerStudio: false);
                            #region 处理显示主界面命令
                            VirtualRoot.Window <ShowMainWindowCommand>("处理显示主界面命令", LogEnum.None,
                                                                       action: message => {
                                UIThread.Execute(() => {
                                    MainWindow mainWindow = this.MainWindow as MainWindow;
                                    if (mainWindow == null)
                                    {
                                        AppContext.Enable();
                                        Views.MainWindow.ShowMainWindow();
                                        // 使状态栏显示显示最新状态
                                        if (NTMinerRoot.Instance.IsMining)
                                        {
                                            var coinShare = NTMinerRoot.Instance.CoinShareSet.GetOrCreate(NTMinerRoot.Instance.CurrentMineContext.MainCoin.GetId());
                                            VirtualRoot.Happened(new ShareChangedEvent(coinShare));
                                            if (NTMinerRoot.Instance.CurrentMineContext is IDualMineContext dualMineContext)
                                            {
                                                coinShare = NTMinerRoot.Instance.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                                                VirtualRoot.Happened(new ShareChangedEvent(coinShare));
                                            }
                                            AppContext.Instance.GpuSpeedVms.Refresh();
                                        }
                                    }
                                    else
                                    {
                                        mainWindow.ShowThisWindow(message.IsToggle);
                                    }
                                });
                            });
                            #endregion
                            splashWindow?.Close();
                            Task.Factory.StartNew(() => {
                                try {
                                    HttpServer.Start($"http://localhost:{WebApiConst.MinerClientPort}");
                                    NTMinerRoot.Instance.Start();
                                }
                                catch (Exception ex) {
                                    Logger.ErrorDebugLine(ex.Message, ex);
                                }
                            });
                        });
                    });
                    Link();
                }
                else
                {
                    try {
                        AppHelper.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerClient);
                    }
                    catch (Exception) {
                        DialogWindow.ShowDialog(message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。", title: "提醒", icon: "Icon_Error");
                        Process currentProcess = Process.GetCurrentProcess();
                        NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
                    }
                }
            }
            base.OnStartup(e);
        }
Example #10
0
 public void Init(Action callback)
 {
     Task.Factory.StartNew(() => {
         bool isWork = Environment.GetCommandLineArgs().Contains("--work", StringComparer.OrdinalIgnoreCase);
         if (isWork)   // 是作业
         {
             DoInit(isWork, callback);
             if (VirtualRoot.IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(true);
             }
         }
         else   // 不是作业
         {
             if (VirtualRoot.IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(false);
             }
             // 如果是Debug模式且不是群控客户端则使用本地数据库初始化
             bool useLocalDb = DevMode.IsDebugMode && !VirtualRoot.IsMinerStudio;
             if (useLocalDb)
             {
                 DoInit(isWork: false, callback: callback);
             }
             else
             {
                 Logger.InfoDebugLine("开始下载server.json");
                 GetAliyunServerJson((data) => {
                     // 如果server.json未下载成功则不覆写本地server.json
                     if (data != null && data.Length != 0)
                     {
                         Logger.InfoDebugLine("GetAliyunServerJson下载成功");
                         var serverJson = Encoding.UTF8.GetString(data);
                         if (!string.IsNullOrEmpty(serverJson))
                         {
                             SpecialPath.WriteServerJsonFile(serverJson);
                         }
                         OfficialServer.GetJsonFileVersionAsync(MainAssemblyInfo.ServerJsonFileName, serverState => {
                             SetServerJsonVersion(serverState.JsonFileVersion);
                             AppVersionChangedEvent.PublishIfNewVersion(serverState.MinerClientVersion);
                             if (Math.Abs((long)Timestamp.GetTimestamp() - (long)serverState.Time) < Timestamp.DesyncSeconds)
                             {
                                 Logger.OkDebugLine("时间同步");
                             }
                             else
                             {
                                 Write.UserWarn($"本机时间和服务器时间不同步,请调整,本地:{DateTime.Now},服务器:{Timestamp.FromTimestamp(serverState.Time)}");
                             }
                             // 因为挖矿端上报算力时会触发加载服务端消息的逻辑所以这里就不加载了
                             if (VirtualRoot.IsMinerStudio)
                             {
                                 VirtualRoot.Execute(new LoadNewServerMessageCommand(serverState.MessageTimestamp));
                             }
                         });
                     }
                     else
                     {
                         if (!File.Exists(SpecialPath.ServerJsonFileFullName))
                         {
                             VirtualRoot.ThisLocalError(nameof(NTMinerRoot), "配置文件下载失败,这是第一次运行开源矿工,配置文件至少需要成功下载一次,请检查网络是否可用", OutEnum.Warn);
                         }
                         else
                         {
                             VirtualRoot.ThisLocalWarn(nameof(NTMinerRoot), "配置文件下载失败,使用最后一次成功下载的配置文件", OutEnum.Warn);
                         }
                     }
                     DoInit(isWork, callback);
                 });
                 #region 发生了用户活动时检查serverJson是否有新版本
                 VirtualRoot.BuildEventPath <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                                              action: message => {
                     RefreshServerJsonFile();
                 });
                 #endregion
             }
         }
         VirtualRoot.ThisLocalInfo(nameof(NTMinerRoot), $"启动{VirtualRoot.AppName}");
     });
 }
Example #11
0
 public void Init(Action callback)
 {
     Task.Factory.StartNew(() => {
         bool isWork = Environment.GetCommandLineArgs().Contains("--work", StringComparer.OrdinalIgnoreCase);
         if (isWork)   // 是作业
         {
             DoInit(isWork, callback);
             if (VirtualRoot.IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(true);
             }
         }
         else   // 不是作业
         {
             if (VirtualRoot.IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(false);
             }
             // 如果是Debug模式且不是群控客户端则使用本地数据库初始化
             bool useLocalDb = DevMode.IsDebugMode && !VirtualRoot.IsMinerStudio;
             if (useLocalDb)
             {
                 DoInit(isWork: false, callback: callback);
             }
             else
             {
                 Logger.InfoDebugLine("开始下载server.json");
                 GetAliyunServerJson((data) => {
                     // 如果server.json未下载成功则不覆写本地server.json
                     if (data != null && data.Length != 0)
                     {
                         Logger.InfoDebugLine("GetAliyunServerJson下载成功");
                         var serverJson = Encoding.UTF8.GetString(data);
                         if (!string.IsNullOrEmpty(serverJson))
                         {
                             SpecialPath.WriteServerJsonFile(serverJson);
                         }
                         OfficialServer.GetJsonFileVersionAsync(MainAssemblyInfo.ServerJsonFileName, (serverJsonFileVersion, minerClientVersion) => {
                             SetServerJsonVersion(serverJsonFileVersion);
                             AppVersionChangedEvent.PublishIfNewVersion(minerClientVersion);
                         });
                     }
                     else
                     {
                         if (!File.Exists(SpecialPath.ServerJsonFileFullName))
                         {
                             VirtualRoot.ThisWorkerError(nameof(NTMinerRoot), "配置文件下载失败,这是第一次运行开源矿工,配置文件至少需要成功下载一次,请检查网络是否可用", OutEnum.Warn);
                         }
                         else
                         {
                             VirtualRoot.ThisWorkerWarn(nameof(NTMinerRoot), "配置文件下载失败,使用最后一次成功下载的配置文件", OutEnum.Warn);
                         }
                     }
                     DoInit(isWork, callback);
                 });
                 #region 发生了用户活动时检查serverJson是否有新版本
                 VirtualRoot.BuildEventPath <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                                              action: message => {
                     RefreshServerJsonFile();
                 });
                 #endregion
             }
         }
         VirtualRoot.ThisWorkerInfo(nameof(NTMinerRoot), "启动");
     });
 }
Example #12
0
        private void DoInit(bool isWork, Action callback)
        {
            this.ServerAppSettingSet = new ServerAppSettingSet(this);
            this.CalcConfigSet       = new CalcConfigSet(this);

            ServerContextInit(isWork);

            this.GpuProfileSet    = new GpuProfileSet(this);
            this.UserSet          = new UserSet();
            this.KernelProfileSet = new KernelProfileSet(this);
            this.GpusSpeed        = new GpusSpeed(this);
            this.CoinShareSet     = new CoinShareSet(this);
            this.MineWorkSet      = new MineWorkSet(this);
            this.MinerGroupSet    = new MinerGroupSet(this);
            this.NTMinerWalletSet = new NTMinerWalletSet(this);
            this.OverClockDataSet = new OverClockDataSet(this);
            this.ColumnsShowSet   = new ColumnsShowSet(this);
            // 作业和在群控客户端管理作业时
            IsJsonLocal        = isWork || VirtualRoot.IsMinerStudio;
            this._minerProfile = new MinerProfile(this);

            // 这几个注册表内部区分挖矿端和群控客户端
            NTMinerRegistry.SetLocation(VirtualRoot.AppFileFullName);
            NTMinerRegistry.SetArguments(string.Join(" ", CommandLineArgs.Args));
            NTMinerRegistry.SetCurrentVersion(MainAssemblyInfo.CurrentVersion.ToString());
            NTMinerRegistry.SetCurrentVersionTag(MainAssemblyInfo.CurrentVersionTag);

            if (VirtualRoot.IsMinerClient)
            {
                OfficialServer.GetTimeAsync((remoteTime) => {
                    if (Math.Abs((DateTime.Now - remoteTime).TotalSeconds) < Timestamp.DesyncSeconds)
                    {
                        Logger.OkDebugLine("时间同步");
                    }
                    else
                    {
                        Write.UserWarn($"本机时间和服务器时间不同步,请调整,本地:{DateTime.Now},服务器:{remoteTime}");
                    }
                });

                Report.Init();
                Link();
                // 当显卡温度变更时守卫温度防线
                TempGruarder.Instance.Init(this);
                // 因为这里耗时500毫秒左右
                Task.Factory.StartNew(() => {
                    Windows.Error.DisableWindowsErrorUI();
                    if (MinerProfile.IsAutoDisableWindowsFirewall)
                    {
                        Windows.Firewall.DisableFirewall();
                    }
                    Windows.UAC.DisableUAC();
                    Windows.WAU.DisableWAUAsync();
                    Windows.Defender.DisableAntiSpyware();
                    Windows.Power.PowerCfgOff();
                    Windows.BcdEdit.IgnoreAllFailures();
                });
            }

            callback?.Invoke();
        }
Example #13
0
        static void Main(string[] args)
        {
            if (args.Length != 0)
            {
                if (args.Contains("--sha1"))
                {
                    File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sha1"), Sha1);
                    return;
                }
            }
            try {
                SystemEvents.SessionEnding += (sender, e) => {
                    OsSessionEndingEvent.ReasonSessionEnding reason;
                    switch (e.Reason)
                    {
                    case SessionEndReasons.Logoff:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Logoff;
                        break;

                    case SessionEndReasons.SystemShutdown:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Shutdown;
                        break;

                    default:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Unknown;
                        break;
                    }
                    VirtualRoot.RaiseEvent(new OsSessionEndingEvent(reason));
                };
                VirtualRoot.StartTimer();
                _waitHandle = new AutoResetEvent(false);
                bool mutexCreated;
                try {
                    _sMutexApp = new Mutex(true, "NTMinerDaemonAppMutex", out mutexCreated);
                }
                catch {
                    mutexCreated = false;
                }
                if (mutexCreated)
                {
                    NTMinerRegistry.SetDaemonVersion(Sha1);
                    NTMinerRegistry.SetAutoBoot("NTMinerDaemon", true);
                    bool isAutoBoot = MinerProfileUtil.GetIsAutoBoot();
                    if (isAutoBoot)
                    {
                        string location = NTMinerRegistry.GetLocation();
                        if (!string.IsNullOrEmpty(location) && File.Exists(location))
                        {
                            string    processName = Path.GetFileName(location);
                            Process[] processes   = Process.GetProcessesByName(processName);
                            if (processes.Length == 0)
                            {
                                string arguments = NTMinerRegistry.GetArguments();
                                if (NTMinerRegistry.GetIsLastIsWork())
                                {
                                    arguments = "--work " + arguments;
                                }
                                try {
                                    Process.Start(location, arguments);
                                    Write.DevOk($"启动挖矿端 {location} {arguments}");
                                }
                                catch (Exception e) {
                                    Logger.ErrorDebugLine($"启动挖矿端失败因为异常 {location} {arguments}", e);
                                }
                            }
                            else
                            {
                                Write.DevDebug($"挖矿端已经在运行中无需启动");
                            }
                        }
                    }
                    else
                    {
                        Write.DevDebug($"挖矿端未设置为自动启动");
                    }
                    Run();
                }
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
            }
        }
Example #14
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            VirtualRoot.Window <UpgradeCommand>(LogEnum.DevConsole,
                                                action: message => {
                AppStatic.Upgrade(message.FileName, message.Callback);
            });
            try {
                appMutex = new Mutex(true, s_appPipName, out createdNew);
            }
            catch (Exception) {
                createdNew = false;
            }

            if (createdNew)
            {
                this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                NTMinerRoot.SetIsMinerClient(false);
                NotiCenterWindow.Instance.Show();
                LoginWindow loginWindow = new LoginWindow();
                var         result      = loginWindow.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    bool isInnerIp = Ip.Util.IsInnerIp(NTMinerRegistry.GetControlCenterHost());
                    if (isInnerIp)
                    {
                        NTMinerServices.NTMinerServicesUtil.RunNTMinerServices(() => {
                            Init();
                        });
                    }
                    else
                    {
                        Init();
                    }
                }
                VirtualRoot.Window <CloseNTMinerCommand>("处理关闭群控客户端命令", LogEnum.UserConsole,
                                                         action: message => {
                    UIThread.Execute(() => {
                        try {
                            if (MainWindow != null)
                            {
                                MainWindow.Close();
                            }
                            Shutdown();
                        }
                        catch (Exception ex) {
                            Logger.ErrorDebugLine(ex);
                            Environment.Exit(0);
                        }
                    });
                });
            }
            else
            {
                try {
                    _appViewFactory.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerStudio);
                }
                catch (Exception) {
                    DialogWindow.ShowDialog(message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。", title: "alert", icon: "Icon_Error");
                    Process currentProcess = Process.GetCurrentProcess();
                    NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
                }
            }
            base.OnStartup(e);
        }
        // 从磁盘读取local.json反序列化为LocalJson对象
        private static void LocalJsonInit()
        {
            if (!_localJsonInited)
            {
                lock (_locker) {
                    if (!_localJsonInited)
                    {
                        _localJsonInited = true;
                        string      localJson   = HomePath.ReadLocalJsonFile(_workType);
                        LocalJsonDb localJsonDb = null;
                        if (!string.IsNullOrEmpty(localJson))
                        {
                            localJsonDb = VirtualRoot.JsonSerializer.Deserialize <LocalJsonDb>(localJson);
                        }
                        if (localJsonDb == null)
                        {
                            if (ClientAppType.IsMinerClient)
                            {
                                localJsonDb = JsonDb.LocalJsonDb.ConvertFromNTMinerContext();
                                VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), "当前作业由本机数据自动生成,因为本机没有作业记录,请先在群控端创建或编辑作业。", OutEnum.Warn, toConsole: true);
                            }
                            else
                            {
                                localJsonDb = new LocalJsonDb();
                            }
                        }
                        _localJsonDb = localJsonDb;

                        if (ClientAppType.IsMinerClient)
                        {
                            #region 因为是群控作业,将开机启动和自动挖矿设置为true
                            var repository = new LiteDbReadWriteRepository <MinerProfileData>(HomePath.LocalDbFileFullName);
                            MinerProfileData localProfile = repository.GetByKey(MinerProfileData.DefaultId);
                            if (localProfile != null)
                            {
                                MinerProfileData.CopyWorkIgnoreValues(localProfile, _localJsonDb.MinerProfile);
                                // 如果是作业模式则必须设置为开机自动重启
                                if (!localProfile.IsAutoBoot)
                                {
                                    localProfile.IsAutoBoot = true;
                                    repository.Update(localProfile);
                                }
                            }
                            _localJsonDb.MinerProfile.IsAutoBoot = true;
                            NTMinerRegistry.SetIsAutoStart(true);
                            #endregion

                            #region 矿机名
                            if (!string.IsNullOrEmpty(_workerName))
                            {
                                _localJsonDb.MinerProfile.MinerName = _workerName;
                            }
                            else
                            {
                                // 当用户使用群控作业但没有指定群控矿机名时使用从local.litedb中读取的矿工名
                                if (string.IsNullOrEmpty(_localJsonDb.MinerProfile.MinerName))
                                {
                                    if (localProfile != null)
                                    {
                                        _localJsonDb.MinerProfile.MinerName = localProfile.MinerName;
                                    }
                                    // 如果local.litedb中也没有矿机名则使用去除了特殊符号的本机机器名作为矿机名
                                    if (string.IsNullOrEmpty(_localJsonDb.MinerProfile.MinerName))
                                    {
                                        _localJsonDb.MinerProfile.MinerName = NTKeyword.GetSafeMinerName(ThisPcName);
                                    }
                                }
                            }
                            #endregion
                        }
                    }
                }
            }
        }
Example #16
0
 static void Main(string[] args)
 {
     if (args.Length != 0)
     {
         if (args.Contains("--sha1"))
         {
             File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sha1"), Sha1);
             return;
         }
     }
     try {
         VirtualRoot.StartTimer();
         if (!Debugger.IsAttached)
         {
             Write.Init();
         }
         _waitHandle = new AutoResetEvent(false);
         bool mutexCreated;
         try {
             _sMutexApp = new Mutex(true, "NTMinerDaemonAppMutex", out mutexCreated);
         }
         catch {
             mutexCreated = false;
         }
         if (mutexCreated)
         {
             NTMinerRegistry.SetDaemonVersion(Sha1);
             NTMinerRegistry.SetAutoBoot("NTMinerDaemon", true);
             bool isAutoBoot = NTMinerRegistry.GetIsAutoBoot();
             if (isAutoBoot)
             {
                 string location = NTMinerRegistry.GetLocation();
                 if (!string.IsNullOrEmpty(location) && File.Exists(location))
                 {
                     string    processName = Path.GetFileName(location);
                     Process[] processes   = Process.GetProcessesByName(processName);
                     if (processes.Length == 0)
                     {
                         string arguments = NTMinerRegistry.GetArguments();
                         if (NTMinerRegistry.GetIsLastIsWork())
                         {
                             arguments = "--work " + arguments;
                         }
                         try {
                             Process.Start(location, arguments);
                             Write.DevOk($"启动挖矿端 {location} {arguments}");
                         }
                         catch (Exception e) {
                             Logger.ErrorDebugLine($"启动挖矿端失败因为异常 {location} {arguments}", e);
                         }
                     }
                     else
                     {
                         Write.DevDebug($"挖矿端已经在运行中无需启动");
                     }
                 }
             }
             else
             {
                 Write.DevDebug($"挖矿端未设置为自动启动");
             }
             Run();
         }
     }
     catch (Exception e) {
         Logger.ErrorDebugLine(e);
     }
 }
Example #17
0
 private void Link()
 {
     VirtualRoot.Window <CloseNTMinerCommand>("处理关闭NTMiner客户端命令", LogEnum.UserConsole,
                                              action: message => {
         UIThread.Execute(() => {
             try {
                 if (MainWindow != null)
                 {
                     MainWindow.Close();
                 }
                 Shutdown();
             }
             catch (Exception e) {
                 Logger.ErrorDebugLine(e);
                 Environment.Exit(0);
             }
         });
     });
     VirtualRoot.Window <CloseMainWindowCommand>("处理关闭主界面命令", LogEnum.DevConsole,
                                                 action: message => {
         UIThread.Execute(() => {
             MainWindow = NotiCenterWindow.Instance;
             foreach (Window window in Windows)
             {
                 if (window != MainWindow)
                 {
                     window.Close();
                 }
             }
             NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage("已切换为无界面模式运行", "开源矿工");
         });
     });
     #region 周期确保守护进程在运行
     Daemon.DaemonUtil.RunNTMinerDaemon();
     VirtualRoot.On <Per20SecondEvent>("周期确保守护进程在运行", LogEnum.DevConsole,
                                       action: message => {
         if (NTMinerRegistry.GetDaemonActiveOn().AddSeconds(20) < DateTime.Now)
         {
             Daemon.DaemonUtil.RunNTMinerDaemon();
         }
     });
     #endregion
     #region 1080小药丸
     VirtualRoot.On <MineStartedEvent>("开始挖矿后启动1080ti小药丸、挖矿开始后如果需要启动DevConsole则启动DevConsole", LogEnum.DevConsole,
                                       action: message => {
         // 启动DevConsole
         if (NTMinerRoot.IsUseDevConsole)
         {
             var mineContext     = message.MineContext;
             string poolIp       = mineContext.MainCoinPool.GetIp();
             string consoleTitle = mineContext.MainCoinPool.Server;
             Daemon.DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
         }
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Start();
     });
     VirtualRoot.On <MineStopedEvent>("停止挖矿后停止1080ti小药丸", LogEnum.DevConsole,
                                      action: message => {
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Stop();
     });
     #endregion
     #region 处理禁用win10系统更新
     VirtualRoot.Window <BlockWAUCommand>("处理禁用win10系统更新命令", LogEnum.DevConsole,
                                          action: message => {
         NTMiner.Windows.WindowsUtil.BlockWAU();
     });
     #endregion
     #region 处理开启A卡计算模式
     VirtualRoot.Window <SwitchRadeonGpuCommand>("处理开启A卡计算模式命令", LogEnum.DevConsole,
                                                 action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             if (NTMinerRoot.Instance.IsMining)
             {
                 NTMinerRoot.Instance.StopMineAsync(() => {
                     SwitchRadeonGpuMode();
                     NTMinerRoot.Instance.StartMine();
                 });
             }
             else
             {
                 SwitchRadeonGpuMode();
             }
         }
     });
     #endregion
     #region 处理A卡驱动签名
     VirtualRoot.Window <AtikmdagPatcherCommand>("处理A卡驱动签名命令", LogEnum.DevConsole,
                                                 action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             if (NTMinerRoot.Instance.IsMining)
             {
                 NTMinerRoot.Instance.StopMineAsync(() => {
                     AtikmdagPatcher.AtikmdagPatcherUtil.Run();
                     NTMinerRoot.Instance.StartMine();
                 });
             }
             else
             {
                 AtikmdagPatcher.AtikmdagPatcherUtil.Run();
             }
         }
     });
     #endregion
 }
Example #18
0
 private void DoRun()
 {
     if (AppUtil.GetMutex(NTKeyword.MinerClientAppMutex))
     {
         NotiCenterWindow.ShowWindow();
         Logger.InfoDebugLine($"==================NTMiner.exe {EntryAssemblyInfo.CurrentVersionStr}==================");
         // 在另一个UI线程运行欢迎界面以确保欢迎界面的响应不被耗时的主界面初始化过程阻塞
         // 注意:必须确保SplashWindow没有用到任何其它界面用到的依赖对象
         SplashWindow splashWindow = null;
         SplashWindow.ShowWindowAsync(window => {
             splashWindow = window;
         });
         if (!NTMiner.Windows.WMI.IsWmiEnabled)
         {
             DialogWindow.ShowHardDialog(new DialogWindowViewModel(
                                             message: "开源矿工无法运行所需的组件,因为本机未开启WMI服务,开源矿工需要使用WMI服务检测windows的内存、显卡等信息,请先手动开启WMI。",
                                             title: "提醒",
                                             icon: "Icon_Error"));
             Shutdown();
             Environment.Exit(0);
         }
         if (!NTMiner.Windows.Role.IsAdministrator)
         {
             NotiCenterWindowViewModel.Instance.Manager
             .CreateMessage()
             .Warning("提示", "请以管理员身份运行。")
             .WithButton("点击以管理员身份运行", button => {
                 WpfUtil.RunAsAdministrator();
             })
             .Dismiss().WithButton("忽略", button => {
             }).Queue();
         }
         BuildPaths();
         NTMinerContext.Instance.Init(() => {
             _appViewFactory.BuildPaths();
             if (VirtualRoot.IsLTWin10)
             {
                 VirtualRoot.ThisLocalWarn(nameof(App), AppRoot.LowWinMessage, toConsole: true);
             }
             if (NTMinerContext.Instance.GpuSet.Count == 0)
             {
                 VirtualRoot.ThisLocalError(nameof(App), "没有矿卡或矿卡未驱动。", toConsole: true);
             }
             if (NTMinerContext.WorkType != WorkType.None && NTMinerContext.Instance.ServerContext.CoinSet.Count == 0)
             {
                 VirtualRoot.ThisLocalError(nameof(App), "访问阿里云失败,请尝试更换本机dns解决此问题。", toConsole: true);
             }
             UIThread.Execute(() => {
                 Window mainWindow  = null;
                 AppRoot.NotifyIcon = ExtendedNotifyIcon.Create("开源矿工", isMinerStudio: false);
                 if (NTMinerRegistry.GetIsNoUi() && NTMinerRegistry.GetIsAutoStart())
                 {
                     ConsoleWindow.Instance.Hide();
                     VirtualRoot.Out.ShowSuccess("以无界面模式启动,可在选项页调整设置", header: "开源矿工");
                 }
                 else
                 {
                     _appViewFactory.ShowMainWindow(isToggle: false, out mainWindow);
                 }
                 // 主窗口显式后退出SplashWindow
                 splashWindow?.Dispatcher.Invoke((Action) delegate() {
                     splashWindow?.OkClose();
                 });
                 // 启动时Windows状态栏显式的是SplashWindow的任务栏图标,SplashWindow关闭后激活主窗口的Windows任务栏图标
                 mainWindow?.Activate();
                 StartStopMineButtonViewModel.Instance.AutoStart();
                 // 注意:因为推迟到这里才启动的计时器,所以别忘了在Upgrade、和Action情况时启动计时器
                 VirtualRoot.StartTimer(new WpfTimingEventProducer());
                 if (CommandLineArgs.Action.TryParse(out MinerClientActionType resourceType))
                 {
                     VirtualRoot.Execute(new MinerClientActionCommand(resourceType));
                 }
                 NTMinerConsole.SetIsMainUiOk(true);
             });
             Task.Factory.StartNew(() => {
                 var minerProfile = NTMinerContext.Instance.MinerProfile;
                 if (minerProfile.IsDisableUAC)
                 {
                     NTMiner.Windows.UAC.DisableUAC();
                 }
                 if (minerProfile.IsAutoDisableWindowsFirewall)
                 {
                     Firewall.DisableFirewall();
                 }
                 if (minerProfile.IsDisableWAU)
                 {
                     NTMiner.Windows.WAU.DisableWAUAsync();
                 }
                 if (minerProfile.IsDisableAntiSpyware)
                 {
                     NTMiner.Windows.Defender.DisableAntiSpyware();
                 }
                 if (!Firewall.IsMinerClientRuleExists())
                 {
                     Firewall.AddMinerClientRule();
                 }
                 try {
                     HttpServer.Start($"http://{NTKeyword.Localhost}:{NTKeyword.MinerClientPort.ToString()}");
                     Daemon.DaemonUtil.RunNTMinerDaemon();
                     NoDevFee.NoDevFeeUtil.RunNTMinerNoDevFee();
                 }
                 catch (Exception ex) {
                     Logger.ErrorDebugLine(ex);
                 }
             });
         });
     }
     else
     {
         try {
             _appViewFactory.ShowMainWindow(this, NTMinerAppType.MinerClient);
         }
         catch (Exception) {
             DialogWindow.ShowSoftDialog(new DialogWindowViewModel(
                                             message: "另一个开源矿工正在运行但唤醒失败,请重试。",
                                             title: "错误",
                                             icon: "Icon_Error"));
             Process currentProcess = Process.GetCurrentProcess();
             NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
         }
     }
 }
Example #19
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            VirtualRoot.Window <UpgradeCommand>(LogEnum.DevConsole,
                                                action: message => {
                AppStatic.Upgrade(message.FileName, message.Callback);
            });
            if (!string.IsNullOrEmpty(CommandLineArgs.Upgrade))
            {
                VirtualRoot.Execute(new UpgradeCommand(CommandLineArgs.Upgrade, () => {
                    UIThread.Execute(() => { Environment.Exit(0); });
                }));
            }
            else
            {
                try {
                    appMutex = new Mutex(true, s_appPipName, out createdNew);
                }
                catch (Exception) {
                    createdNew = false;
                }
                if (createdNew)
                {
                    Logger.InfoDebugLine($"==================NTMiner.exe {NTMinerRoot.CurrentVersion.ToString()}==================");
                    if (!NTMiner.Windows.WMI.IsWmiEnabled)
                    {
                        DialogWindow.ShowDialog(message: "开源矿工无法运行所需的组件,因为本机未开启WMI服务,开源矿工需要使用WMI服务检测windows的内存、显卡等信息,请先手动开启WMI。", title: "提醒", icon: "Icon_Error");
                        Shutdown();
                        Environment.Exit(0);
                    }
                    NTMinerOverClockUtil.ExtractResource();

                    NTMinerRoot.SetIsMinerClient(true);
                    NotiCenterWindowViewModel.IsHotKeyEnabled = true;
                    Window splashWindow = _appViewFactory.CreateSplashWindow();
                    splashWindow.Show();
                    NotiCenterWindow.Instance.Show();
                    if (DevMode.IsDevMode)
                    {
                        HandlerIdsWindow window = new HandlerIdsWindow();
                        window.Show();
                    }
                    if (!NTMiner.Windows.Role.IsAdministrator)
                    {
                        NotiCenterWindowViewModel.Instance.Manager
                        .CreateMessage()
                        .Warning("请以管理员身份运行。")
                        .WithButton("点击以管理员身份运行", button => {
                            Wpf.Util.RunAsAdministrator();
                        })
                        .Dismiss().WithButton("忽略", button => {
                        }).Queue();
                    }
                    VirtualRoot.On <StartingMineFailedEvent>("开始挖矿失败", LogEnum.DevConsole,
                                                             action: message => {
                        AppContext.Instance.MinerProfileVm.IsMining = false;
                        Write.UserFail(message.Message);
                    });
                    NTMinerRoot.Instance.Init(() => {
                        _appViewFactory.Link();
                        if (NTMinerRoot.Instance.GpuSet.Count == 0)
                        {
                            NotiCenterWindowViewModel.Instance.Manager.ShowErrorMessage("没有矿卡或矿卡未驱动。");
                        }
                        UIThread.Execute(() => {
                            if (NTMinerRoot.GetIsNoUi() && NTMinerRegistry.GetIsAutoStart())
                            {
                                MainWindow = NotiCenterWindow.Instance;
                                NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage("已切换为无界面模式运行", "开源矿工");
                            }
                            else
                            {
                                _appViewFactory.ShowMainWindow(isToggle: false);
                            }
                            AppContext.NotifyIcon = ExtendedNotifyIcon.Create("开源矿工", isMinerStudio: false);
                            splashWindow?.Close();
                        });
                        #region 处理显示主界面命令
                        VirtualRoot.Window <ShowMainWindowCommand>("处理显示主界面命令", LogEnum.DevConsole,
                                                                   action: message => {
                            ShowMainWindow(message.IsToggle);
                        });
                        #endregion
                        Task.Factory.StartNew(() => {
                            try {
                                HttpServer.Start($"http://localhost:{Consts.MinerClientPort}");
                                NTMinerRoot.Instance.Start();
                            }
                            catch (Exception ex) {
                                Logger.ErrorDebugLine(ex);
                            }
                        });
                    });
                    Link();
                }
                else
                {
                    try {
                        _appViewFactory.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerClient);
                    }
                    catch (Exception) {
                        DialogWindow.ShowDialog(message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。", title: "提醒", icon: "Icon_Error");
                        Process currentProcess = Process.GetCurrentProcess();
                        NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
                    }
                }
            }
            base.OnStartup(e);
        }
Example #20
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            try {
                appMutex = new Mutex(true, s_appPipName, out createdNew);
            }
            catch (Exception) {
                createdNew = false;
            }

            if (createdNew)
            {
                Vms.AppStatic.IsMinerClient = false;
                SplashWindow splashWindow = new SplashWindow();
                splashWindow.Show();
                NotiCenterWindow.Instance.Show();
                NTMinerRoot.AppName = "开源矿工群控客户端";
                NTMinerServices.NTMinerServicesUtil.RunNTMinerServices();
                NTMinerRoot.Current.Init(() => {
                    NTMinerRoot.KernelDownloader = new KernelDownloader();
                    UIThread.Execute(() => {
                        splashWindow?.Close();
                        bool?result = true;
                        if (Ip.Util.IsInnerIp(NTMinerRegistry.GetControlCenterHost()))
                        {
                            SingleUser.LoginName = "innerip";
                            SingleUser.SetPasswordSha1("123");
                            result = true;
                        }
                        else if (string.IsNullOrEmpty(SingleUser.LoginName) || string.IsNullOrEmpty(SingleUser.PasswordSha1))
                        {
                            LoginWindow loginWindow = new LoginWindow();
                            result = loginWindow.ShowDialog();
                        }
                        if (result.HasValue && result.Value)
                        {
                            ChartsWindow.ShowWindow();
                            System.Drawing.Icon icon = new System.Drawing.Icon(GetResourceStream(new Uri("pack://application:,,,/MinerStudio;component/logo.ico")).Stream);
                            AppHelper.NotifyIcon     = ExtendedNotifyIcon.Create(icon, "群控客户端", isMinerStudio: true);
                            #region 处理显示主界面命令
                            VirtualRoot.Window <ShowMainWindowCommand>("处理显示主界面命令", LogEnum.None,
                                                                       action: message => {
                                Dispatcher.Invoke((ThreadStart)ChartsWindow.ShowWindow);
                            });
                            #endregion
                            HttpServer.Start($"http://localhost:{WebApiConst.MinerStudioPort}");
                            AppHelper.RemoteDesktop = MsRdpRemoteDesktop.OpenRemoteDesktop;
                        }
                    });
                });
                VirtualRoot.Window <CloseNTMinerCommand>("处理关闭群控客户端命令", LogEnum.UserConsole,
                                                         action: message => {
                    UIThread.Execute(() => {
                        if (MainWindow != null)
                        {
                            MainWindow.Close();
                        }
                        Shutdown();
                        Environment.Exit(0);
                    });
                });
            }
            else
            {
                try {
                    AppHelper.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerStudio);
                }
                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);
        }
Example #21
0
 static void Main(string[] args)
 {
     SetOut(new ConsoleOut());
     if (args.Length != 0)
     {
         if (args.Contains("--sha1", StringComparer.OrdinalIgnoreCase))
         {
             File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sha1"), Sha1);
             return;
         }
     }
     try {
         SystemEvents.SessionEnding += SessionEndingEventHandler;
         StartTimer();
         _waitHandle = new AutoResetEvent(false);
         bool mutexCreated;
         try {
             _sMutexApp = new Mutex(true, "NTMinerDaemonAppMutex", out mutexCreated);
         }
         catch {
             mutexCreated = false;
         }
         if (mutexCreated)
         {
             if (!DevMode.IsDevMode)
             {
                 NTMinerConsole.Disable();
             }
             NTMinerRegistry.SetDaemonVersion(Sha1);
             NTMinerRegistry.SetAutoBoot("NTMinerDaemon", true);
             if (!CommandLineArgs.Args.Contains("--bootByMinerClient"))
             {
                 #region 是否自动启动挖矿端
                 bool isAutoBoot = MinerProfileUtil.GetIsAutoBoot();
                 if (isAutoBoot)
                 {
                     string location = NTMinerRegistry.GetLocation(NTMinerAppType.MinerClient);
                     if (!string.IsNullOrEmpty(location) && File.Exists(location))
                     {
                         string    processName = Path.GetFileName(location);
                         Process[] processes   = Process.GetProcessesByName(processName);
                         if (processes.Length == 0)
                         {
                             string arguments = NTMinerRegistry.GetMinerClientArguments(NTMinerAppType.MinerClient);
                             try {
                                 Process.Start(location, arguments);
                                 NTMinerConsole.DevOk(() => $"启动挖矿端 {location} {arguments}");
                             }
                             catch (Exception e) {
                                 Logger.ErrorDebugLine($"启动挖矿端失败因为异常 {location} {arguments}", e);
                             }
                         }
                         else
                         {
                             NTMinerConsole.DevDebug($"挖矿端已经在运行中无需启动");
                         }
                     }
                 }
                 #endregion
             }
             Run();
         }
     }
     catch (Exception e) {
         Logger.ErrorDebugLine(e);
     }
 }
Example #22
0
 public void Init(Action callback)
 {
     Task.Factory.StartNew(() => {
         bool isSelfWork = Environment.GetCommandLineArgs().Contains("--selfWork", StringComparer.OrdinalIgnoreCase);
         bool isWork     = isSelfWork || Environment.GetCommandLineArgs().Contains("--work", StringComparer.OrdinalIgnoreCase);
         _workType       = isSelfWork ? WorkType.SelfWork : (isWork ? WorkType.MineWork : WorkType.None);
         if (ClientAppType.IsMinerClient)
         {
             NTMinerRegistry.SetWorkType(_workType);
         }
         if (isWork)
         {
             DoInit(callback);
         }
         else
         {
             // 如果是Debug模式且不是群控客户端则使用本地数据库初始化
             bool useLocalDb = DevMode.IsDevMode && !ClientAppType.IsMinerStudio;
             if (useLocalDb)
             {
                 DoInit(callback);
             }
             else
             {
                 Logger.InfoDebugLine(nameof(RpcRoot.OSSService.AliyunOSSService.GetAliyunServerJson));
                 RpcRoot.OSSService.AliyunOSSService.GetAliyunServerJson((data) => {
                     // 如果server.json未下载成功则不覆写本地server.json
                     if (data != null && data.Length != 0)
                     {
                         Logger.InfoDebugLine($"{nameof(RpcRoot.OSSService.AliyunOSSService.GetAliyunServerJson)} ok");
                         var serverJson = Encoding.UTF8.GetString(data);
                         if (!string.IsNullOrEmpty(serverJson))
                         {
                             HomePath.WriteServerJsonFile(serverJson);
                         }
                         RpcRoot.OfficialServer.AppSettingService.GetJsonFileVersionAsync(HomePath.ExportServerJsonFileName, serverState => {
                             SetServerJsonVersion(serverState.JsonFileVersion);
                             AppVersionChangedEvent.PublishIfNewVersion(serverState.MinerClientVersion);
                             if (Math.Abs((long)Timestamp.GetTimestamp() - (long)serverState.Time) >= Timestamp.DesyncSeconds)
                             {
                                 NTMinerConsole.UserWarn($"本机和服务器时间不同步,请调整,本地:{DateTime.Now.ToString()},服务器:{Timestamp.FromTimestamp(serverState.Time).ToString()}。此问题不影响挖矿。");
                             }
                         });
                     }
                     else
                     {
                         if (!File.Exists(HomePath.ServerJsonFileFullName))
                         {
                             VirtualRoot.ThisLocalError(nameof(NTMinerContext), "配置文件下载失败,这是第一次运行开源矿工,配置文件至少需要成功下载一次,请检查网络是否可用", OutEnum.Warn);
                         }
                         else
                         {
                             VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), "配置文件下载失败,使用最近一次成功下载的配置文件");
                         }
                     }
                     DoInit(callback);
                 });
                 #region 发生了用户活动时检查serverJson是否有新版本
                 VirtualRoot.AddEventPath <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                                            action: message => {
                     RefreshServerJsonFile();
                 }, location: this.GetType());
                 #endregion
             }
         }
         VirtualRoot.ThisLocalInfo(nameof(NTMinerContext), $"启动{VirtualRoot.AppName}");
     });
 }
Example #23
0
        private void DoInit(bool isWork, Action callback)
        {
            this.PackageDownloader = new PackageDownloader(this);
            this.AppSettingSet     = new AppSettingSet(this);
            this.CalcConfigSet     = new CalcConfigSet(this);

            ContextInit(isWork);

            // 打码支持内核品牌
            if (!string.IsNullOrEmpty(CommandLineArgs.KernelBrand))
            {
                if (SysDicItemSet.TryGetDicItem("KernelBrand", CommandLineArgs.KernelBrand, out ISysDicItem brandItem))
                {
                    #region KernelBrandId
                    string brand = $"KernelBrandId{brandItem.GetId()}KernelBrandId";
                    byte[] data  = Encoding.UTF8.GetBytes(brand);
                    if (data.Length != KernelBrandRaw.Length)
                    {
                        throw new InvalidProgramException();
                    }
                    byte[] source = File.ReadAllBytes(ClientId.AppFileFullName);
                    int    index  = 0;
                    for (int i = 0; i < source.Length - KernelBrandRaw.Length; i++)
                    {
                        int j = 0;
                        for (; j < KernelBrandRaw.Length; j++)
                        {
                            if (source[i + j] != KernelBrandRaw[j])
                            {
                                break;
                            }
                        }
                        if (j == KernelBrandRaw.Length)
                        {
                            index = i;
                            break;
                        }
                    }
                    for (int i = index; i < index + data.Length; i++)
                    {
                        source[i] = data[i - index];
                    }
                    string brandExeFullName = Path.Combine(Path.GetDirectoryName(ClientId.AppFileFullName), Path.GetFileNameWithoutExtension(ClientId.AppFileFullName) + $"_{CommandLineArgs.KernelBrand}.exe");
                    File.WriteAllBytes(brandExeFullName, source);
                    #endregion
                    Environment.Exit(0);
                    return;
                }
            }

            this.UserSet          = new UserSet();
            this.KernelProfileSet = new KernelProfileSet(this);
            this.GpusSpeed        = new GpusSpeed(this);
            this.CoinShareSet     = new CoinShareSet(this);
            this.MineWorkSet      = new MineWorkSet(this);
            this.MinerGroupSet    = new MinerGroupSet(this);
            this.OverClockDataSet = new OverClockDataSet(this);
            this.ColumnsShowSet   = new ColumnsShowSet(this);
            MineWorkData mineWorkData = null;
            if (isWork)
            {
                mineWorkData = LocalJson.MineWork;
            }
            this._minerProfile = new MinerProfile(this, mineWorkData);

            // 这几个注册表内部区分挖矿端和群控客户端
            NTMinerRegistry.SetLocation(ClientId.AppFileFullName);
            NTMinerRegistry.SetArguments(string.Join(" ", CommandLineArgs.Args));
            NTMinerRegistry.SetCurrentVersion(CurrentVersion.ToString());
            NTMinerRegistry.SetCurrentVersionTag(CurrentVersionTag);

            #region 发生了用户活动时检查serverJson是否有新版本
            VirtualRoot.On <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                             action: message => {
                OfficialServer.GetJsonFileVersionAsync(AssemblyInfo.ServerJsonFileName, (jsonFileVersion) => {
                    if (!string.IsNullOrEmpty(jsonFileVersion) && JsonFileVersion != jsonFileVersion)
                    {
                        SpecialPath.GetAliyunServerJson((data) => {
                            Write.DevLine($"有新版本{JsonFileVersion}->{jsonFileVersion}");
                            string rawJson = Encoding.UTF8.GetString(data);
                            SpecialPath.WriteServerJsonFile(rawJson);
                            ReInitServerJson();
                            bool isUseJson = !DevMode.IsDebugMode || VirtualRoot.IsMinerStudio;
                            if (isUseJson)
                            {
                                // 作业模式下界面是禁用的,所以这里的初始化isWork必然是false
                                ContextReInit(isWork: false);
                                Logger.InfoDebugLine("刷新完成");
                            }
                            else
                            {
                                Write.DevLine("不是使用的json,无需刷新");
                            }
                            JsonFileVersion = jsonFileVersion;
                        });
                    }
                    else
                    {
                        Write.DevLine("server.json没有新版本", ConsoleColor.Green);
                    }
                });
            });
            #endregion

            callback?.Invoke();
        }
 public void RefreshIcon()
 {
     _targetNotifyIcon.Visible = _isMinerStudio || NTMinerRegistry.GetIsShowNotifyIcon();
 }
Example #25
0
 private void Link()
 {
     VirtualRoot.Window <CloseNTMinerCommand>("处理关闭NTMiner客户端命令", LogEnum.UserConsole,
                                              action: message => {
         UIThread.Execute(() => {
             try {
                 if (MainWindow != null)
                 {
                     MainWindow.Close();
                 }
                 Shutdown();
             }
             catch (Exception e) {
                 Logger.ErrorDebugLine(e);
                 Environment.Exit(0);
             }
         });
     });
     VirtualRoot.Window <CloseMainWindowCommand>("处理关闭主界面命令", LogEnum.DevConsole,
                                                 action: message => {
         UIThread.Execute(() => {
             MainWindow = NotiCenterWindow.Instance;
             foreach (Window window in Windows)
             {
                 if (window != MainWindow)
                 {
                     window.Close();
                 }
             }
             NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage(message.Message, "开源矿工");
         });
     });
     #region 周期确保守护进程在运行
     Daemon.DaemonUtil.RunNTMinerDaemon();
     VirtualRoot.On <Per20SecondEvent>("周期确保守护进程在运行", LogEnum.DevConsole,
                                       action: message => {
         if (NTMinerRegistry.GetDaemonActiveOn().AddSeconds(20) < DateTime.Now)
         {
             Daemon.DaemonUtil.RunNTMinerDaemon();
         }
     });
     #endregion
     #region 1080小药丸
     VirtualRoot.On <MineStartedEvent>("开始挖矿后启动1080ti小药丸、挖矿开始后如果需要启动DevConsole则启动DevConsole", LogEnum.DevConsole,
                                       action: message => {
         // 启动DevConsole
         if (NTMinerRoot.IsUseDevConsole)
         {
             var mineContext     = message.MineContext;
             string poolIp       = mineContext.MainCoinPool.GetIp();
             string consoleTitle = mineContext.MainCoinPool.Server;
             Daemon.DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
         }
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Start();
     });
     VirtualRoot.On <MineStopedEvent>("停止挖矿后停止1080ti小药丸", LogEnum.DevConsole,
                                      action: message => {
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Stop();
     });
     #endregion
     #region 处理禁用win10系统更新
     VirtualRoot.Window <BlockWAUCommand>("处理禁用win10系统更新命令", LogEnum.DevConsole,
                                          action: message => {
         NTMiner.Windows.WindowsUtil.BlockWAU();
     });
     #endregion
     #region 优化windows
     VirtualRoot.Window <Win10OptimizeCommand>("处理优化windows命令", LogEnum.DevConsole,
                                               action: message => {
         NTMiner.Windows.WindowsUtil.Win10Optimize();
     });
     #endregion
     #region 处理开启A卡计算模式
     VirtualRoot.Window <SwitchRadeonGpuCommand>("处理开启A卡计算模式命令", LogEnum.DevConsole,
                                                 action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             SwitchRadeonGpuMode();
         }
     });
     #endregion
     #region 处理A卡驱动签名
     VirtualRoot.Window <AtikmdagPatcherCommand>("处理A卡驱动签名命令", LogEnum.DevConsole,
                                                 action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             AtikmdagPatcher.AtikmdagPatcherUtil.Run();
         }
     });
     #endregion
     #region 启用或禁用windows远程桌面
     VirtualRoot.Window <EnableOrDisableWindowsRemoteDesktopCommand>("处理启用或禁用Windows远程桌面命令", LogEnum.DevConsole,
                                                                     action: message => {
         string msg = "确定启用Windows远程桌面吗?";
         if (!message.IsEnable)
         {
             msg = "确定禁用Windows远程桌面吗?";
             return;
         }
         DialogWindow.ShowDialog(message: msg, title: "确认", onYes: () => {
             if (message.IsEnable)
             {
                 Rdp.SetRdpEnabled(true, true);
                 Firewall.AddRemoteDesktopRule();
             }
             else
             {
                 Rdp.SetRdpEnabled(false, true);
                 Firewall.RemoveRemoteDesktopRule();
             }
         }, icon: IconConst.IconConfirm);
     });
     #endregion
     #region 启用或禁用windows开机自动登录
     VirtualRoot.Window <EnableOrDisableWindowsAutoLoginCommand>("处理启用或禁用Windows开机自动登录命令", LogEnum.DevConsole,
                                                                 action: message => {
         if (NTMiner.Windows.OS.Instance.IsAutoAdminLogon)
         {
             return;
         }
         NTMiner.Windows.Cmd.RunClose("control", "userpasswords2");
     });
     #endregion
 }