/// <summary>
        /// Starts init.d script on Linux.
        /// </summary>
        /// <param name="ScriptName">Name of the init.d script to start.</param>
        /// <param name="Args">Arguments for the command.</param>
        /// <returns>true if the function succeeded, false otherwise.</returns>
        public static bool RunInitdScript(string ScriptName, string Args)
        {
            log.Trace("(ScriptName:'{0}',Args:'{1}')", ScriptName, Args);
            bool res = false;

            if (!SystemInfo.CurrentRuntime.IsLinux())
            {
                res = true;
                log.Trace("(-)[NOT_LINUX]:{0}", res);
                return(res);
            }

            string         scriptFile = string.Format("/etc/init.d/{0}", ScriptName);
            ConsoleProcess script     = new ConsoleProcess(scriptFile, Args);

            log.Debug("Starting '{0}'.", script.GetCommandLine());
            if (script.RunAndWaitSuccessExit())
            {
                log.Debug("'{0}' succeeded.", ScriptName);
                res = true;
            }
            else
            {
                log.Error("'{0}' failed.", ScriptName);
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Uninstalls package by executing apt-get remove.
        /// </summary>
        /// <param name="PackageName">Package to uninstall.</param>
        /// <returns>true if the function succeeds, false otherwise.</returns>
        public static bool UninstallAptGetPackage(string PackageName)
        {
            log.Trace("(FileName:'{0}')", PackageName);

            bool res = false;

            try
            {
                ConsoleProcess process = new ConsoleProcess("apt-get", string.Format("remove -qy {0}", PackageName));
                if (process.RunAndWaitSuccessExit(120000))
                {
                    res = true;
                }
                else
                {
                    log.Error("Executing '{0}' failed.", process.GetCommandLine());
                }
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Executes schtasks command on Windows.
        /// </summary>
        /// <param name="Arguments">Arguments for schtasks command.</param>
        /// <returns>true if the function succeeded, false otherwise.</returns>
        public static bool Schtasks(string Arguments)
        {
            log.Trace("(Arguments:'{0}')", Arguments);
            bool res = false;

            if (!SystemInfo.CurrentRuntime.IsWindows())
            {
                res = true;
                log.Trace("(-)[NOT_WINDOWS]:{0}", res);
                return(res);
            }

            ConsoleProcess schtasks = new ConsoleProcess("schtasks.exe", Arguments);

            log.Debug("Starting '{0}'.", schtasks.GetCommandLine());
            if (schtasks.RunAndWaitSuccessExit())
            {
                log.Debug("schtasks succeeded.");
                res = true;
            }
            else
            {
                log.Error("schtasks failed.");
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Locates file on Linux using which.
        /// </summary>
        /// <param name="FileName">Name of file to look for.</param>
        /// <returns>Result of which or null if the function failed.</returns>
        public static string Which(string FileName)
        {
            log.Trace("(FileName:'{0}')", FileName);
            string res = null;

            if (!SystemInfo.CurrentRuntime.IsLinux())
            {
                log.Trace("(-)[NOT_LINUX]:'{0}'", res);
                return(res);
            }

            ConsoleProcess which = new ConsoleProcess("which", FileName);

            log.Debug("Starting '{0}'.", which.GetCommandLine());
            if (which.RunAndWaitSuccessExit())
            {
                List <string> outputLines = which.GetOutput();
                if (outputLines.Count > 0)
                {
                    res = outputLines[0].Trim();
                }
                if (string.IsNullOrEmpty(res))
                {
                    res = null;
                }
            }
            else
            {
                log.Error("Which on '{0}' failed.", FileName);
            }

            log.Trace("(-):'{0}'", res);
            return(res);
        }
        /// <summary>
        /// Executes update-rc.d on Linux.
        /// </summary>
        /// <param name="Args">Arguments for the command.</param>
        /// <returns>true if the function succeeded, false otherwise.</returns>
        public static bool UpdateRcd(string Args)
        {
            log.Trace("(Args:'{0}')", Args);
            bool res = false;

            if (!SystemInfo.CurrentRuntime.IsLinux())
            {
                res = true;
                log.Trace("(-)[NOT_LINUX]:{0}", res);
                return(res);
            }

            ConsoleProcess updateRcd = new ConsoleProcess("update-rc.d", Args);

            log.Debug("Starting '{0}'.", updateRcd.GetCommandLine());
            if (updateRcd.RunAndWaitSuccessExit())
            {
                log.Debug("update-rc.d succeeded.");
                res = true;
            }
            else
            {
                log.Error("update-rc.d failed.");
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Change access rights of file on Linux using chmod.
        /// </summary>
        /// <param name="Path">Path to file or folder.</param>
        /// <param name="AccessRights">chmod access rights.</param>
        /// <returns>true if the function succeeded, false otherwise.</returns>
        public static bool Chmod(string Path, string AccessRights)
        {
            log.Trace("(Path:'{0}',AccessRights:'{1}')", Path, AccessRights);
            bool res = false;

            if (!SystemInfo.CurrentRuntime.IsLinux())
            {
                res = true;
                log.Trace("(-)[NOT_LINUX]:{0}", res);
                return(res);
            }

            ConsoleProcess chmod = new ConsoleProcess("chmod", string.Format("{0} \"{1}\"", AccessRights, Path));

            log.Debug("Starting '{0}'.", chmod.GetCommandLine());
            if (chmod.RunAndWaitSuccessExit())
            {
                log.Debug("Access rights of '{0}' changed.", Path);
                res = true;
            }
            else
            {
                log.Error("chmod on '{0}' failed.", Path);
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Change owner of file or folder on Linux using chown.
        /// </summary>
        /// <param name="Path">Path to file or folder.</param>
        /// <returns>true if the function succeeded, false otherwise.</returns>
        public static bool Chown(string Path)
        {
            log.Trace("(Path:'{0}')", Path);
            bool res = false;

            if (!SystemInfo.CurrentRuntime.IsLinux())
            {
                res = true;
                log.Trace("(-)[NOT_LINUX]:{0}", res);
                return(res);
            }

            if (string.IsNullOrEmpty(Program.SudoUserGroup))
            {
                res = true;
                log.Trace("(-)[NOT_SUDO]:{0}", res);
                return(res);
            }

            ConsoleProcess chown = new ConsoleProcess("chown", string.Format("-R {0} \"{1}\"", Program.SudoUserGroup, Path));

            log.Debug("Starting '{0}'.", chown.GetCommandLine());
            if (chown.RunAndWaitSuccessExit())
            {
                log.Debug("Owner of '{0}' changed.", Path);
                res = true;
            }
            else
            {
                log.Error("chown on '{0}' failed.", Path);
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Installs the file to the system.
        /// </summary>
        /// <returns>true if the function succeeds, false otherwise.</returns>
        public override bool Install()
        {
            log.Trace("()");

            bool res = false;

            unpackDirectoryName = AskForEmptyDirectory(string.Format("Where do you want to install <white>{0}</white>? [{1}] ", Name, unpackDirectoryName), unpackDirectoryName);

            CUI.WriteRich("Downloading <white>{0}</white>... ", Name);
            if (DownloadFileToTemp(uri))
            {
                CUI.WriteOk();
                CUI.WriteRich("Unpacking <white>{0}</white>... ", Name);
                try
                {
                    ConsoleProcess tgz = new ConsoleProcess("tar", string.Format("-xzf \"{0}\" -C \"{1}\" --overwrite", downloadedFileName, unpackDirectoryName));
                    if (tgz.RunAndWaitSuccessExit(20000))
                    {
                        CUI.WriteOk();

                        Chown(unpackDirectoryName);

                        if (savePathAs != null)
                        {
                            GeneralConfiguration.SharedValues.Add(savePathAs, unpackDirectoryName);
                            if (internalPath != null)
                            {
                                GeneralConfiguration.SharedValues.Add(savePathAs + "-InternalPath", Path.Combine(unpackDirectoryName, internalPath));
                            }
                        }

                        Status |= InstallationFileStatus.Unpacked;
                        res     = true;
                    }
                    else
                    {
                        CUI.WriteFailed();
                    }
                }
                catch (Exception e)
                {
                    log.Error("Exception occurred: {0}", e.ToString());
                    CUI.WriteFailed();
                }
            }
            else
            {
                log.Error("Failed to download file from URI '{0}'.", uri);
                CUI.WriteFailed();
            }

            if (!res)
            {
                Uninstall();
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Generates PFX certificate using OpenSSL.
        /// </summary>
        /// <param name="OpenSsl">Path to OpenSSL.</param>
        /// <param name="PfxFile">Path where to store the final PFX file.</param>
        /// <returns>true if the function succeeds, false otherwise.</returns>
        public static bool GeneratePfxCertificate(string OpenSsl, string PfxFile)
        {
            log.Trace("(OpenSsl:'{0}',PfxFile:'{1}')", OpenSsl, PfxFile);

            bool res = false;

            string opensslScriptContents;

            if (SystemInfo.CurrentRuntime.IsWindows())
            {
                // On Windows we have to create script to run OpenSSL with environmental variable pointing to the OpenSSL configuration file.
                string path = System.Reflection.Assembly.GetEntryAssembly().Location;
                path = Path.GetDirectoryName(path);
                path = Path.Combine(path, "openssl.cfg");

                opensslScriptContents =
                    string.Format(
                        "@set \"OPENSSL_CONF={0}\"\n"
                        + "@\"{1}\" req -x509 -newkey rsa:4096 -keyout cert.key -out cert.cer -days 365000 -subj \"/C=FM\" -passout pass:1234\n"
                        + "@\"{1}\" pkcs12 -export -out \"{2}\" -inkey cert.key -in cert.cer -passin pass:1234 -passout \"pass:\"\n"
                        + "@del cert.key\n"
                        + "@del cert.cer\n",
                        path, OpenSsl, PfxFile);
            }
            else
            {
                opensslScriptContents =
                    string.Format(
                        "\"{0}\" req -x509 -newkey rsa:4096 -keyout cert.key -out cert.cer -days 365000 -subj \"/C=FM\" -passout pass:1234\n"
                        + "\"{0}\" pkcs12 -export -out \"{1}\" -inkey cert.key -in cert.cer -passin pass:1234 -passout \"pass:\"\n"
                        + "rm cert.key\n"
                        + "rm cert.cer\n",
                        OpenSsl, PfxFile);
            }

            string opensslScript = Path.Combine(TemporaryDirectoryName, SystemInfo.CurrentRuntime.IsLinux() ? "gencert.sh" : "gencert.cmd");

            if (CreateFileWriteTextChown(opensslScript, opensslScriptContents))
            {
                ConsoleProcess scriptProcess = SystemInfo.CurrentRuntime.IsLinux() ? new ConsoleProcess("bash", string.Format("-x ./{0}", opensslScript)) : new ConsoleProcess("cmd.exe", string.Format("/C {0}", opensslScript));
                if (scriptProcess.RunAndWaitSuccessExit(20000))
                {
                    Chown(PfxFile);
                    res = File.Exists(PfxFile);
                }
                else
                {
                    log.Error("Certificate generation script failed.");
                }
            }
            else
            {
                log.Error("Unable to write certificate generation script to '{0}'.", opensslScript);
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #10
0
        public override bool Configure()
        {
            log.Trace("()");

            bool res = false;

            Dictionary <string, string> conf;

            if (!ConfigurationByRid.TryGetValue(SystemInfo.CurrentRuntime.Rid, out conf))
            {
                log.Trace("(-)[UNSUPPORTED]:{0}", res);
                return(res);
            }

            bool done = false;

            while (!done)
            {
                string appDataDir = Environment.ExpandEnvironmentVariables(conf["Application data directory"]);

                string dataDir = InstallationFile.AskForEmptyDirectory(string.Format("Where do you want <white>CAN server application data</white> to be stored? [{0}] ", appDataDir), appDataDir);
                conf["Application data directory"] = dataDir;
                GeneralConfiguration.SharedValues.Add("Can-DataDir", dataDir);

                string confFile = Path.Combine(dataDir, conf["Configuration file"]);


                int apiPort = int.Parse(conf["API port"]);
                while (GeneralConfiguration.UsedPorts.ContainsKey(apiPort))
                {
                    apiPort++;
                }
                conf["API port"] = apiPort.ToString();
                log.Debug("Selected port {0} as CAN server's API port.", apiPort);
                GeneralConfiguration.UsedPorts.Add(apiPort, "CAN server API interface");
                GeneralConfiguration.SharedValues.Add("CAN server API interface", apiPort.ToString());


                int swarmPort = int.Parse(conf["Swarm port"]);
                swarmPort          = AskForOpenPort(string.Format("Please enter a port number for <white>CAN server swarm interface</white>. This port will have to be open and publicly accessible from the Internet. [{0}] ", swarmPort), swarmPort, "CAN server swarm interface");
                conf["Swarm port"] = swarmPort.ToString();

                int gatewayPort = int.Parse(conf["Gateway port"]);
                gatewayPort          = AskForOpenPort(string.Format("Please enter a port number for <white>CAN server gateway interface</white>. This port will have to be open and publicly accessible from the Internet. [{0}] ", gatewayPort), gatewayPort, "CAN server gateway interface");
                conf["Gateway port"] = gatewayPort.ToString();


                string ipfs = SystemInfo.CurrentRuntime.IsLinux() ? Path.Combine(GeneralConfiguration.SharedValues["CanDir"], "ipfs") : Path.Combine(GeneralConfiguration.SharedValues["CanDir"], "ipfs.exe");

                string initIpfsScript        = SystemInfo.CurrentRuntime.IsLinux() ? Path.Combine(InstallationFile.TemporaryDirectoryName, "ipfsinit.sh") : Path.Combine(InstallationFile.TemporaryDirectoryName, "ipfsinit.cmd");
                string initIpfsScriptContent = SystemInfo.CurrentRuntime.IsLinux() ?
                                               string.Format("#/bin/base\n"
                                                             + "\n"
                                                             + "export IOPCAN_PATH=\"{0}\"\n"
                                                             + "\"{1}\" init\n", dataDir, ipfs)
          :
                                               string.Format("@set \"IOPCAN_PATH={0}\"\n"
                                                             + "\"{1}\" init\n", dataDir, ipfs);


                CUI.WriteRich("Creating <white>CAN server init script</white>... ");
                if (InstallationFile.CreateFileWriteTextChown(initIpfsScript, initIpfsScriptContent))
                {
                    CUI.WriteOk();
                    CUI.WriteRich("Creating <white>CAN server daemon script</white>... ");

                    string daemonIpfsScript = SystemInfo.CurrentRuntime.IsLinux() ? Path.Combine(GeneralConfiguration.SharedValues["CanDir"], "iop-can") : Path.Combine(GeneralConfiguration.SharedValues["CanDir"], "iop-can.cmd");
                    GeneralConfiguration.SharedValues[Name + "-executable"]      = daemonIpfsScript;
                    GeneralConfiguration.SharedValues[Name + "-executable-args"] = string.Format("\"{0}\"", daemonIpfsScript);

                    string daemonIpfsScriptContent = SystemInfo.CurrentRuntime.IsLinux() ?
                                                     string.Format("#/bin/base\n"
                                                                   + "\n"
                                                                   + "export IOPCAN_PATH=\"{0}\"\n"
                                                                   + "\"{1}\" daemon &\n", dataDir, ipfs)
            :
                                                     string.Format("@set \"IOPCAN_PATH={0}\"\n"
                                                                   + "\"{1}\" daemon\n", dataDir, ipfs);

                    if (InstallationFile.CreateFileWriteTextChown(daemonIpfsScript, daemonIpfsScriptContent))
                    {
                        CUI.WriteOk();
                        done = true;

                        CUI.WriteRich("Starting <white>CAN server init script</white>... ");
                        ConsoleProcess initScriptProcess = SystemInfo.CurrentRuntime.IsLinux() ? new ConsoleProcess("bash", string.Format("-x ./{0}", initIpfsScript)) : new ConsoleProcess("cmd.exe", string.Format("/C {0}", initIpfsScript));
                        if (initScriptProcess.RunAndWaitSuccessExit(20000))
                        {
                            CUI.WriteOk();

                            InstallationFile.Chown(dataDir);

                            CUI.WriteRich("Loading <white>CAN server configuration file</white>... ");
                            try
                            {
                                string[] lines = File.ReadAllLines(confFile);
                                CUI.WriteOk();

                                bool          addressesSection = false;
                                List <string> confLines        = new List <string>();
                                foreach (string line in lines)
                                {
                                    string confLine = line;

                                    if (addressesSection)
                                    {
                                        if (confLine.Contains("/ip4/0.0.0.0/tcp/14001"))
                                        {
                                            confLine = confLine.Replace("tcp/14001", string.Format("tcp/{0}", conf["Swarm port"]));
                                        }
                                        else if (confLine.Contains("ip6/::/tcp/14001"))
                                        {
                                            confLine = confLine.Replace("tcp/14001", string.Format("tcp/{0}", conf["Swarm port"]));
                                        }
                                        else if (confLine.Contains("/ip4/127.0.0.1/tcp/15001"))
                                        {
                                            confLine = confLine.Replace("tcp/15001", string.Format("tcp/{0}", conf["API port"]));
                                        }
                                        else if (confLine.Contains("/ip4/127.0.0.1/tcp/18080"))
                                        {
                                            confLine = confLine.Replace("tcp/18080", string.Format("tcp/{0}", conf["Gateway port"]));
                                        }
                                        else if (confLine.Trim().EndsWith("},"))
                                        {
                                            addressesSection = false;
                                        }
                                    }
                                    else
                                    {
                                        addressesSection = confLine.Contains("\"Addresses\":");
                                    }

                                    confLines.Add(confLine);
                                }


                                CUI.WriteRich("Writing new <white>CAN server configuration file</white>... ");
                                if (InstallationFile.CreateFileWriteTextChown(confFile, string.Join("\n", confLines)))
                                {
                                    CUI.WriteOk();

                                    res = true;
                                }
                                else
                                {
                                    CUI.WriteFailed();
                                    CUI.WriteRich("<red>ERROR:</red> unable to write to file <white>{0}</white>.\n", confFile);
                                }
                            }
                            catch (Exception e)
                            {
                                log.Error("Exception occurred: {0}", e.ToString());
                                CUI.WriteFailed();
                                CUI.WriteRich("<red>ERROR:</red> unable to read file <white>{0}</white>.\n", confFile);
                            }
                        }
                        else
                        {
                            CUI.WriteFailed();
                        }
                    }
                    else
                    {
                        CUI.WriteFailed();
                        CUI.WriteRich("<red>ERROR:</red> unable to write to <white>{0}</white>. Please try again.\n", daemonIpfsScript);
                    }

                    try
                    {
                        File.Delete(initIpfsScript);
                    }
                    catch (Exception e)
                    {
                        log.Error("Exception occurred: {0}", e.ToString());
                    }
                }
                else
                {
                    CUI.WriteFailed();
                    CUI.WriteRich("<red>ERROR:</red> unable to write to <white>{0}</white>. Please try again.\n", initIpfsScript);
                }
            }


            log.Trace("(-):{0}", res);
            return(res);
        }
Example #11
0
        public override bool Configure()
        {
            log.Trace("()");

            bool res = false;

            Dictionary <string, string> conf;

            if (!ConfigurationByRid.TryGetValue(SystemInfo.CurrentRuntime.Rid, out conf))
            {
                log.Trace("(-)[UNSUPPORTED]:{0}", res);
                return(res);
            }

            bool   rpcPublic            = false;
            int    rpcPort              = int.Parse(conf["RPC port"]);
            string rpcUser              = conf["RPC user"];
            string rpcPassword          = "******";
            string miningLicense        = "";
            string miningToAddress      = "";
            string miningLicensePrivKey = "";
            bool   miningEnabled        = false;
            bool   rpcEnabled           = false;
            string dataDir              = "";
            string confFile             = "";

            while (!res)
            {
                string appDataDir = Environment.ExpandEnvironmentVariables(conf["Application data directory"]);

                dataDir = InstallationFile.AskForEmptyDirectory(string.Format("Where do you want <white>IoP Blockchain Core wallet application data</white> to be stored? [{0}] ", appDataDir), appDataDir);
                conf["Application data directory"] = dataDir;
                GeneralConfiguration.SharedValues.Add("CoreWallet-DataDir", dataDir);

                confFile = Path.Combine(dataDir, conf["Configuration file"]);

                int mainPort = int.Parse(conf["Main port"]);
                mainPort          = AskForOpenPort(string.Format("Please enter a port number for <white>Core wallet P2P interface</white>. This port will have to be open and publicly accessible from the Internet. [{0}] ", mainPort), mainPort, "Core wallet P2P interface");
                conf["Main port"] = mainPort.ToString();

                CUI.WriteRich("Would you like to run <white>Core wallet RPC server</white> (this is required if you want to mine)? [<white>N</white>O / <white>y</white>es] ");
                rpcEnabled = CUI.ReadKeyAnswer(new char[] { 'n', 'y' }) == 'y';
                if (rpcEnabled)
                {
                    CUI.WriteRich("Would you like the <white>RPC server</white> to be accessible from the Internet? [<white>N</white>O / <white>y</white>es] ");
                    rpcPublic = CUI.ReadKeyAnswer(new char[] { 'n', 'y' }) == 'y';

                    if (rpcPublic)
                    {
                        rpcPort = AskForOpenPort(string.Format("Please enter a port number for <white>Core wallet RPC interface</white>. This port will have to be open and publicly accessible from the Internet. If you changed your mind and you do not want the RPC server to be accessible from the Internet, enter 0. [{0}] ", rpcPort), rpcPort, "Core wallet RPC interface", true);
                        if (rpcPort != 0)
                        {
                            conf["RPC port"] = rpcPort.ToString();
                        }
                        else
                        {
                            rpcPublic = false;
                        }
                    }


                    CUI.WriteRich("Enter RPC user name: [{0}] ", rpcUser);
                    rpcUser          = CUI.ReadStringAnswer(rpcUser);
                    conf["RPC user"] = rpcUser;

                    CUI.WriteRich("Enter RPC password: [{0}] ", rpcPassword);
                    rpcPassword = CUI.ReadStringAnswer(rpcPassword);

                    CUI.WriteRich("Do you have a mining license and would you like to run a miner? [<white>N</white>O / <white>y</white>es] ");
                    miningEnabled = CUI.ReadKeyAnswer(new char[] { 'n', 'y' }) == 'y';
                    if (miningEnabled)
                    {
                        CUI.WriteRich("Enter your mining license address (or press ENTER if you changed your mind): ");
                        miningLicense = CUI.ReadStringAnswer(miningLicense);

                        if (!string.IsNullOrEmpty(miningLicense))
                        {
                            CUI.WriteRich("Enter the private key for your mining license. <yellow>Note that If you entered a wrong mining license or if you enter wrong private key, this installer will not recognize it, but your Core wallet may fail to start.</yellow> Private key (or press ENTER if you changed your mind): ");
                            miningLicensePrivKey = CUI.ReadStringAnswer(miningLicensePrivKey);

                            if (!string.IsNullOrEmpty(miningLicensePrivKey))
                            {
                                CUI.WriteRich("Enter the address to which the newly minted coins should be sent (or press ENTER to generate the address automatically): ");
                                miningToAddress = CUI.ReadStringAnswer(miningToAddress);
                            }
                            else
                            {
                                miningEnabled = false;
                                miningLicense = "";
                            }
                        }
                        else
                        {
                            miningEnabled = false;
                        }
                    }
                }

                string confFileContents = ConfigurationFileTemplate
                                          .Replace("$MAIN_PORT", conf["Main port"])
                                          .Replace("$ENABLE_RPC", rpcEnabled ? "1" : "0")
                                          .Replace("$RPC_USER", conf["RPC user"])
                                          .Replace("$RPC_PASSWORD", rpcPassword)
                                          .Replace("$RPC_PORT", conf["RPC port"])
                                          .Replace("$ENABLE_MINING", "0")
                                          .Replace("$MINING_LICENSE", miningLicense)
                                          .Replace("$MINE_TO_ADDR", miningToAddress);

                CUI.WriteRich("Writing <white>Core wallet's configuration</white> with mining DISABLED to <white>{0}</white>... ", confFile);
                if (InstallationFile.CreateFileWriteTextChown(confFile, confFileContents))
                {
                    CUI.WriteOk();
                    res = true;
                }
                else
                {
                    CUI.WriteFailed();
                    CUI.WriteRich("<red>ERROR:</red> unable to write to <white>{0}</white>. Please try again.\n", confFile);
                }
            }

            string iopd = null;

            if (res)
            {
                iopd = SystemInfo.CurrentRuntime.IsLinux() ? InstallationFile.Which("IoPd") : Path.Combine(GeneralConfiguration.SharedValues["CoreWalletDir-InternalPath"], "IoPd.exe");
                GeneralConfiguration.SharedValues[Name + "-executable"]      = iopd;
                GeneralConfiguration.SharedValues[Name + "-executable-args"] = string.Format("\"{0}\" -datadir=\"{1}\"", iopd, GeneralConfiguration.SharedValues["CoreWallet-DataDir"]);
            }

            if (res && miningEnabled)
            {
                log.Trace("Configuring mining.");
                CUI.WriteRich("The basic configuration of <white>Core Wallet</white> is complete, but as you wanted to enable mining, some more configuration is needed. "
                              + "Please be patient, it won't take long. If this step fails, the installation will continue and your <white>Core Wallet</white> will be fully setup except for the mining.\n");

                bool miningSetupOk        = false;
                bool saveNewConfiguration = false;

                string iopCli = SystemInfo.CurrentRuntime.IsLinux() ? InstallationFile.Which("IoP-cli") : Path.Combine(GeneralConfiguration.SharedValues["CoreWalletDir-InternalPath"], "IoP-cli.exe");

                CUI.WriteRich("Looking for <white>IoPd</white>... ");
                log.Debug("IoPd location is '{0}'.", iopd);
                if (File.Exists(iopd))
                {
                    CUI.WriteOk();

                    CUI.WriteRich("Looking for <white>IoP-cli</white>... ");
                    log.Debug("IoP-cli location is '{0}'.", iopCli);

                    if (File.Exists(iopCli))
                    {
                        CUI.WriteOk();

                        CUI.WriteRich("Starting <white>IoPd</white>... ");
                        ConsoleProcess iopdProcess = new ConsoleProcess(iopd, string.Format("-datadir=\"{0}\"", dataDir));
                        if (iopdProcess.Run())
                        {
                            Thread.Sleep(5000);
                            CUI.WriteOk();

                            CUI.WriteRich("Starting <white>IoP-cli</white> to import the private key... ");
                            ConsoleProcess iopCliProcess = new ConsoleProcess(iopCli, string.Format("-rpcconnect=127.0.0.1 -rpcport={0} -rpcuser={1} -rpcpassword={2} importprivkey {3}", rpcPort, rpcUser, rpcPassword, miningLicensePrivKey));
                            if (iopCliProcess.RunAndWaitSuccessExit())
                            {
                                CUI.WriteOk();

                                if (string.IsNullOrEmpty(miningToAddress))
                                {
                                    CUI.WriteRich("Starting <white>IoP-cli</white> to generate mining-to address... ");
                                    iopCliProcess = new ConsoleProcess(iopCli, string.Format("-rpcconnect=127.0.0.1 -rpcport={0} -rpcuser={1} -rpcpassword={2} getnewaddress", rpcPort, rpcUser, rpcPassword));
                                    if (iopCliProcess.RunAndWaitSuccessExit())
                                    {
                                        List <string> outputLines = iopCliProcess.GetOutput();
                                        if (outputLines.Count != 0)
                                        {
                                            miningToAddress = outputLines[0].Trim();
                                            CUI.WriteOk();

                                            CUI.WriteRich("Your newly generated mining-to address is: <white>{0}</white>\n", miningToAddress);

                                            saveNewConfiguration = true;
                                        }
                                        else
                                        {
                                            log.Error("Invalid output received from IoP-cli.");
                                            CUI.WriteFailed();
                                        }
                                    }
                                    else
                                    {
                                        log.Error("Unable to start IoP-cli or it failed.");
                                        CUI.WriteFailed();
                                    }
                                }
                            }
                            else
                            {
                                log.Error("Unable to start IoP-cli or it failed.");
                                CUI.WriteFailed();
                            }


                            CUI.WriteRich("Starting <white>IoP-cli</white> to stop IoPd... ");
                            iopCliProcess = new ConsoleProcess(iopCli, string.Format("-rpcconnect=127.0.0.1 -rpcport={0} -rpcuser={1} -rpcpassword={2} stop", rpcPort, rpcUser, rpcPassword));
                            if (iopCliProcess.RunAndWaitSuccessExit())
                            {
                                CUI.WriteOk();
                            }
                            else
                            {
                                CUI.WriteFailed();
                            }

                            CUI.WriteRich("Waiting for <white>IoP-cli</white> to stop... ");
                            if (iopdProcess.WaitSuccessExit(15000))
                            {
                                CUI.WriteOk();
                            }
                            else
                            {
                                CUI.WriteFailed();
                                CUI.WriteLine("IoPd will now be killed.");
                                iopdProcess.KillProcess();
                            }
                        }
                        else
                        {
                            log.Error("Unable to start IoPd.");
                            CUI.WriteFailed();
                        }
                    }
                    else
                    {
                        log.Error("Unable to find IoP-cli.");
                        CUI.WriteFailed();
                    }
                }
                else
                {
                    log.Error("Unable to find IoPd.");
                    CUI.WriteFailed();
                }


                if (saveNewConfiguration)
                {
                    string confFileContents = ConfigurationFileTemplate
                                              .Replace("$MAIN_PORT", conf["Main port"])
                                              .Replace("$ENABLE_RPC", rpcEnabled ? "1" : "0")
                                              .Replace("$RPC_USER", conf["RPC user"])
                                              .Replace("$RPC_PASSWORD", rpcPassword)
                                              .Replace("$RPC_PORT", conf["RPC port"])
                                              .Replace("$ENABLE_MINING", "1")
                                              .Replace("$MINING_LICENSE", miningLicense)
                                              .Replace("$MINE_TO_ADDR", miningToAddress);

                    CUI.WriteRich("Writing <white>Core wallet's configuration</white> with mining ENABLED to <white>{0}</white>... ", confFile);
                    if (InstallationFile.CreateFileWriteTextChown(confFile, confFileContents))
                    {
                        CUI.WriteOk();
                        miningSetupOk = true;
                    }
                    else
                    {
                        CUI.WriteFailed();
                        CUI.WriteRich("<red>ERROR:</red> unable to write to <white>{0}</white>.\n", confFile);
                    }
                }

                if (miningSetupOk)
                {
                    CUI.WriteRich("Configuration of <white>Core wallet</white> for mining <green>SUCCEEDED</green>.\n");
                }
                else
                {
                    CUI.WriteRich("<red>Configuration of Core wallet for mining failed.</red>\n");
                }
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #12
0
        /// <summary>
        /// Obtains .NET Core Runtime identifier of the current system.
        /// </summary>
        /// <returns>Runtime identifier of the current system.</returns>
        private static RuntimeInfo GetSystemRuntimeInfo()
        {
            log.Trace("()");

            Rid rid = Rid.Unknown;

            try
            {
                // We only support x64 architecture.
                if (RuntimeInformation.OSArchitecture == Architecture.X64)
                {
                    string desc = RuntimeInformation.OSDescription.ToLowerInvariant().Trim();
                    log.Debug("OS description '{0}'.", desc);

                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        log.Debug("Windows platform detected.");

                        string winstr = "microsoft windows ";
                        if (desc.StartsWith(winstr))
                        {
                            string ver = desc.Substring(winstr.Length);
                            log.Debug("Windows version '{0}' detected.", ver);

                            if (ver.StartsWith("6.1."))
                            {
                                rid = Rid.win7_x64;
                            }
                            else if (ver.StartsWith("6.2."))
                            {
                                rid = Rid.win8_x64;
                            }
                            else if (ver.StartsWith("6.3."))
                            {
                                rid = Rid.win81_x64;
                            }
                            else if (ver.StartsWith("10.0."))
                            {
                                rid = Rid.win10_x64;
                            }
                            else
                            {
                                log.Error("Windows version '{0}' is not supported.", ver);
                            }
                        }
                        else
                        {
                            log.Error("Invalid or unsupported Windows OS description '{0}'.", desc);
                        }
                    }
                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        log.Debug("Linux platform detected.");

                        bool isUbuntu = desc.Contains("ubuntu");
                        bool isDebian = desc.Contains("debian");
                        if (isUbuntu || isDebian)
                        {
                            ConsoleProcess lsb = new ConsoleProcess("lsb_release", "-r");
                            if (lsb.RunAndWaitSuccessExit())
                            {
                                List <string> lines = lsb.GetOutput();
                                if ((lines != null) && (lines.Count > 0))
                                {
                                    string ver = lines[0].Trim();
                                    int    li  = ver.LastIndexOf(':');
                                    ver = ver.Substring(li + 1).Trim();

                                    if (isUbuntu)
                                    {
                                        if (ver.StartsWith("16.10"))
                                        {
                                            rid = Rid.ubuntu_16_10_x64;
                                        }
                                        else if (ver.StartsWith("16.04"))
                                        {
                                            rid = Rid.ubuntu_16_04_x64;
                                        }
                                        else if (ver.StartsWith("14.10"))
                                        {
                                            rid = Rid.ubuntu_14_10_x64;
                                        }
                                        else if (ver.StartsWith("14.04"))
                                        {
                                            rid = Rid.ubuntu_14_04_x64;
                                        }
                                        else
                                        {
                                            log.Error("Ubuntu version '{0}' is not supported.", ver);
                                        }
                                    }
                                    else
                                    {
                                        if (ver.StartsWith("8."))
                                        {
                                            rid = Rid.debian_8_x64;
                                        }
                                        else
                                        {
                                            log.Error("Debian version '{0}' is not supported.", ver);
                                        }
                                    }
                                }
                                else
                                {
                                    log.Error("Empty output of 'lsb_release -r' received.");
                                }
                            }
                            else
                            {
                                log.Error("Executing '{0}' failed.", lsb.GetCommandLine());
                            }
                        }
                        else
                        {
                            log.Error("This Linux distro is not supported.");
                        }
                    }
                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    {
                        log.Debug("OSX platform detected.");

                        string osxstr = "darwin ";
                        if (desc.StartsWith(osxstr))
                        {
                            string ver = desc.Substring(osxstr.Length);
                            log.Debug("OS X version '{0}' detected.", ver);

                            if (ver.StartsWith("14."))
                            {
                                rid = Rid.osx_10_10_x64;
                            }
                            else if (ver.StartsWith("15."))
                            {
                                rid = Rid.osx_10_11_x64;
                            }
                            else if (ver.StartsWith("16."))
                            {
                                rid = Rid.osx_10_12_x64;
                            }
                            else
                            {
                                log.Error("OS X version '{0}' is not supported.", ver);
                            }
                        }
                        else
                        {
                            log.Error("Invalid or unsupported OS X description '{0}'.", desc);
                        }
                    }
                    else
                    {
                        log.Error("Unknown OS platform, OS description is '{0}'.", RuntimeInformation.OSDescription);
                    }
                }
                else
                {
                    log.Error("OS architecture {0} is not supported.", RuntimeInformation.OSArchitecture);
                }
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }

            RuntimeInfo res = new RuntimeInfo(rid);

            log.Trace("(-):{0}", res);
            return(res);
        }