Ejemplo n.º 1
0
        public void Run(string[] args)
        {
            INetworkSet networkSet = AltNetworkSets.Bitcoin;
            var         argsConf   = new TextFileConfiguration(args);
            var         debug      = argsConf.GetOrDefault <bool>("debug", false);

            ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(debug), null, loggerProcessor)));

            using (var interactive = new Interactive())
            {
                var config = new TumblerConfiguration();
                config.LoadArgs(networkSet, args);
                try
                {
                    var runtime = TumblerRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ServerInteractiveRuntime(runtime);
                    StoppableWebHost host = null;
                    if (!config.OnlyMonitor)
                    {
                        host = new StoppableWebHost(() => new WebHostBuilder()
                                                    .UseAppConfiguration(runtime)
                                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                                    .UseStartup <Startup>()
                                                    .Build());
                    }

                    var job = new BroadcasterJob(interactive.Runtime.Services);
                    job.Start();
                    interactive.Services.Add(job);

                    var tor = new TorRegisterJob(config, runtime);
                    tor.Start();
                    interactive.Services.Add(tor);

                    if (!config.OnlyMonitor)
                    {
                        host.Start();
                        interactive.Services.Add(host);
                    }

                    interactive.StartInteractive();
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (InterruptedConsoleException) { }
                catch (Exception exception)
                {
                    Logs.Tumbler.LogError("Exception thrown while running the server");
                    Logs.Tumbler.LogError(exception.ToString());
                }
            }
        }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            Logs.Configure(new FuncLoggerFactory(i => new ConsoleLogger(i, (a, b) => true, false)));
            var configuration = new TumblerConfiguration();

            configuration.LoadArgs(args);
            try
            {
                IWebHost         host     = null;
                ExternalServices services = null;
                if (!configuration.OnlyMonitor)
                {
                    host = new WebHostBuilder()
                           .UseKestrel()
                           .UseAppConfiguration(configuration)
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .UseIISIntegration()
                           .UseStartup <Startup>()
                           .Build();
                    services = (ExternalServices)host.Services.GetService(typeof(ExternalServices));
                }
                else
                {
                    services = ExternalServices.CreateFromRPCClient(configuration.RPC.ConfigureRPCClient(configuration.Network), new DBreezeRepository(Path.Combine(configuration.DataDir, "db")));
                }

                CancellationTokenSource cts = new CancellationTokenSource();
                var job = new BroadcasterJob(services, Logs.Main);
                job.Start(cts.Token);
                Logs.Main.LogInformation("BroadcasterJob started");

                if (!configuration.OnlyMonitor)
                {
                    host.Run();
                }
                else
                {
                    Console.ReadLine();
                }
                cts.Cancel();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Main.LogError(ex.Message);
                }
            }
            catch (Exception exception)
            {
                Logs.Main.LogError("Exception thrown while running the server " + exception.Message);
            }
        }
Ejemplo n.º 3
0
        public async Task Initialize()
        {
            // Start broadcasterJob (onlymonitor mode)
            if (this.broadcasterJob == null || !this.broadcasterJob.Started)
            {
                var config = new FullNodeTumblerClientConfiguration(this.TumblingState, onlyMonitor: true);
                this.runtime = await TumblerClientRuntime.FromConfigurationAsync(config).ConfigureAwait(false);

                this.broadcasterJob = this.runtime.CreateBroadcasterJob();
                this.broadcasterJob.Start();
            }
        }
Ejemplo n.º 4
0
        public void Run(string[] args)
        {
            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false)));

            using (var interactive = new Interactive())
            {
                var config = new TumblerConfiguration();
                config.LoadArgs(args);
                try
                {
                    var runtime = TumblerRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ServerInteractiveRuntime(runtime);
                    StoppableWebHost host = null;
                    if (!config.OnlyMonitor)
                    {
                        host = new StoppableWebHost(() => new WebHostBuilder()
                                                    .UseKestrel()
                                                    .UseAppConfiguration(runtime)
                                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                                    .UseStartup <Startup>()
                                                    .UseUrls(config.GetUrls()).Build());
                    }

                    var job = new BroadcasterJob(interactive.Runtime.Services);
                    job.Start();
                    interactive.Services.Add(job);

                    if (!config.OnlyMonitor)
                    {
                        host.Start();
                        interactive.Services.Add(host);
                    }

                    interactive.StartInteractive();
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (InterruptedConsoleException) { }
                catch (Exception exception)
                {
                    Logs.Tumbler.LogError("Exception thrown while running the server");
                    Logs.Tumbler.LogError(exception.ToString());
                }
            }
        }
Ejemplo n.º 5
0
        public static void Main(string[] args)
        {
            Logs.Configure(new FuncLoggerFactory(i => new ConsoleLogger("Configuration", (a, b) => true, false)));
            var logger        = new ConsoleLogger("Main", (a, b) => true, false);
            var configuration = new TumblerConfiguration();

            configuration.LoadArgs(args);
            try
            {
                var host = new WebHostBuilder()
                           .UseKestrel()
                           .UseAppConfiguration(configuration)
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .UseIISIntegration()
                           .UseStartup <Startup>()
                           .Build();

                var services = (ExternalServices)host.Services.GetService(typeof(ExternalServices));
                CancellationTokenSource cts = new CancellationTokenSource();
                var job = new BroadcasterJob(services, logger);
                job.Start(cts.Token);
                host.Run();
                cts.Cancel();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    logger.LogError(ex.Message);
                }
            }
            catch (Exception exception)
            {
                logger.LogError("Exception thrown while running the server " + exception.Message);
            }
        }
Ejemplo n.º 6
0
        /// <inheritdoc />
        public async Task TumbleAsync(string originWalletName, string destinationWalletName, string originWalletPassword)
        {
            // Make sure it won't start new tumbling round if already started
            if (this.State == TumbleState.Tumbling)
            {
                this.logger.LogDebug("Tumbler is already running");
                throw new Exception("Tumbling is already running");
            }

            this.tumblingState.TumblerUri = new Uri(this.TumblerAddress);

            // Check if in initial block download
            if (!this.chain.IsDownloaded())
            {
                this.logger.LogDebug("Chain is still being downloaded: " + this.chain.Tip);
                throw new Exception("Chain is still being downloaded");
            }

            Wallet destinationWallet = this.walletManager.GetWallet(destinationWalletName);
            Wallet originWallet      = this.walletManager.GetWallet(originWalletName);

            // Check if origin wallet has a sufficient balance to begin tumbling at least 1 cycle
            Money originBalance = this.walletManager.GetSpendableTransactionsInWallet(this.tumblingState.OriginWalletName)
                                  .Sum(s => s.Transaction.Amount);

            // Should ideally take network's transaction fee into account too, but that is dynamic
            if (originBalance <= (this.TumblerParameters.Denomination + this.TumblerParameters.Fee))
            {
                this.logger.LogDebug("Insufficient funds in origin wallet");
                throw new Exception("Insufficient funds in origin wallet");
            }

            // Check if password is valid before starting any cycles
            try
            {
                HdAddress tempAddress = originWallet.GetAccountsByCoinType(this.tumblingState.CoinType).First()
                                        .GetFirstUnusedReceivingAddress();
                originWallet.GetExtendedPrivateKeyForAddress(originWalletPassword, tempAddress);
            }
            catch (Exception)
            {
                this.logger.LogDebug("Origin wallet password appears to be invalid");
                throw new Exception("Origin wallet password appears to be invalid");
            }

            // Update the state and save
            this.tumblingState.DestinationWallet     = destinationWallet ?? throw new Exception($"Destination wallet not found. Have you created a wallet with name {destinationWalletName}?");
            this.tumblingState.DestinationWalletName = destinationWalletName;
            this.tumblingState.OriginWallet          = originWallet ?? throw new Exception($"Origin wallet not found. Have you created a wallet with name {originWalletName}?");
            this.tumblingState.OriginWalletName      = originWalletName;
            this.tumblingState.OriginWalletPassword  = originWalletPassword;

            var accounts = this.tumblingState.DestinationWallet.GetAccountsByCoinType(this.tumblingState.CoinType);
            // TODO: Possibly need to preserve destination account name in tumbling state. Default to first account for now
            string    accountName = accounts.First().Name;
            HdAccount destAccount = this.tumblingState.DestinationWallet.GetAccountByCoinType(accountName, this.tumblingState.CoinType);
            string    key         = destAccount.ExtendedPubKey;
            KeyPath   keyPath     = new KeyPath("0");

            // Stop and dispose onlymonitor
            if (this.broadcasterJob != null && this.broadcasterJob.Started)
            {
                await this.broadcasterJob.Stop().ConfigureAwait(false);
            }
            this.runtime?.Dispose();

            // Bypass Tor for integration tests
            FullNodeTumblerClientConfiguration config;

            if (this.TumblerAddress.Contains("127.0.0.1"))
            {
                config = new FullNodeTumblerClientConfiguration(this.tumblingState, onlyMonitor: false,
                                                                connectionTest: false, useProxy: false);
            }
            else
            {
                config = new FullNodeTumblerClientConfiguration(this.tumblingState, onlyMonitor: false,
                                                                connectionTest: false, useProxy: true);
            }

            this.runtime = await TumblerClientRuntime.FromConfigurationAsync(config).ConfigureAwait(false);

            BitcoinExtPubKey extPubKey = new BitcoinExtPubKey(key, this.runtime.Network);

            if (key != null)
            {
                this.runtime.DestinationWallet =
                    new ClientDestinationWallet(extPubKey, keyPath, this.runtime.Repository, this.runtime.Network);
            }
            this.TumblerParameters = this.runtime.TumblerParameters;

            // Run onlymonitor mode
            this.broadcasterJob = this.runtime.CreateBroadcasterJob();
            this.broadcasterJob.Start();

            // Run tumbling mode
            this.stateMachine = new StateMachinesExecutor(this.runtime);
            this.stateMachine.Start();

            this.State = TumbleState.Tumbling;
        }
Ejemplo n.º 7
0
        public void StartTumbler(BreezeConfiguration breezeConfig, bool getConfigOnly, string ntumblebitServerConf = null, string datadir = null)
        {
            var argsTemp = new List <string>();

            argsTemp.Add("-debug");

            if (breezeConfig.TumblerNetwork == Network.TestNet)
            {
                argsTemp.Add("-testnet");
            }
            else if (breezeConfig.TumblerNetwork == Network.RegTest)
            {
                argsTemp.Add("-regtest");
            }
            // No else needed, mainnet is defaulted

            if (ntumblebitServerConf != null)
            {
                argsTemp.Add("-conf=" + ntumblebitServerConf);
            }

            if (datadir != null)
            {
                argsTemp.Add("-datadir=" + datadir);
            }

            string[] args     = argsTemp.ToArray();
            var      argsConf = new TextFileConfiguration(args);
            var      debug    = argsConf.GetOrDefault <bool>("debug", false);

            ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(debug), false, loggerProcessor)));

            if (getConfigOnly)
            {
                config = new TumblerConfiguration();
                config.LoadArgs(args);
                runtime = TumblerRuntime.FromConfiguration(config, new AcceptAllClientInteraction());
                return;
            }

            using (var interactive = new Interactive())
            {
                config = new TumblerConfiguration();
                config.LoadArgs(args);
                try
                {
                    runtime             = TumblerRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ServerInteractiveRuntime(runtime);
                    StoppableWebHost host = null;
                    if (!config.OnlyMonitor)
                    {
                        host = new StoppableWebHost(() => new WebHostBuilder()
                                                    .UseAppConfiguration(runtime)
                                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                                    .UseStartup <Startup>()
                                                    .Build());
                    }

                    var job = new BroadcasterJob(interactive.Runtime.Services);
                    job.Start();
                    interactive.Services.Add(job);

                    var tor = new TorRegisterJob(config, runtime);
                    tor.Start();
                    interactive.Services.Add(tor);

                    if (!config.OnlyMonitor)
                    {
                        host.Start();
                        interactive.Services.Add(host);
                    }

                    interactive.StartInteractive();
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (InterruptedConsoleException) { }
                catch (Exception exception)
                {
                    Logs.Tumbler.LogError("Exception thrown while running the server");
                    Logs.Tumbler.LogError(exception.ToString());
                }
            }
        }
Ejemplo n.º 8
0
        public void StartTumbler(BreezeConfiguration breezeConfig, bool getConfigOnly, string ntumblebitServerConf = null, string dataDir = null, bool torMandatory = true, TumblerProtocolType?tumblerProtocol = null)
        {
            var argsTemp = new List <string>();

            argsTemp.Add("-debug");

            if (breezeConfig.TumblerNetwork == Network.TestNet)
            {
                argsTemp.Add("-testnet");
            }
            else if (breezeConfig.TumblerNetwork == Network.RegTest)
            {
                argsTemp.Add("-regtest");
            }
            // No else needed, mainnet is defaulted

            if (ntumblebitServerConf != null)
            {
                argsTemp.Add("-conf=" + ntumblebitServerConf);
            }

            if (dataDir != null)
            {
                argsTemp.Add("-datadir=" + dataDir);
            }

            if (tumblerProtocol.HasValue)
            {
                argsTemp.Add($"-tumblerProtocol={tumblerProtocol.Value}");
            }

            string[] args     = argsTemp.ToArray();
            var      argsConf = new TextFileConfiguration(args);
            var      debug    = argsConf.GetOrDefault <bool>("debug", false);

            ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();

            if (dataDir == null)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ImpleumNode");
                    dataDir = argsConf.GetOrDefault <string>("dataDir", dataDir);
                }
                else
                {
                    dataDir = Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".impleumnode");
                    dataDir = argsConf.GetOrDefault <string>("dataDir", dataDir);
                }
            }

            string logDir = Path.Combine(dataDir, breezeConfig.TumblerNetwork.RootFolderName, breezeConfig.TumblerNetwork.Name, "Logs");

            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(debug), false, loggerProcessor)), logDir);

            if (getConfigOnly)
            {
                config = new TumblerConfiguration();
                if (!torMandatory)
                {
                    config.TorMandatory = false;
                }

                config.LoadArgs(args);
                runtime = TumblerRuntime.FromConfiguration(config, new AcceptAllClientInteraction());
                return;
            }

            using (var interactive = new Interactive())
            {
                config = new TumblerConfiguration();
                config.LoadArgs(args);

                if (!torMandatory)
                {
                    config.TorMandatory = false;
                }

                try
                {
                    runtime             = TumblerRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ServerInteractiveRuntime(runtime);
                    StoppableWebHost host = null;
                    if (!config.OnlyMonitor)
                    {
                        host = new StoppableWebHost(() => new WebHostBuilder()
                                                    .UseAppConfiguration(runtime)
                                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                                    .UseStartup <Startup>()
                                                    .Build());
                    }

                    var job = new BroadcasterJob(interactive.Runtime.Services);
                    job.Start();
                    interactive.Services.Add(job);

                    var tor = new TorRegisterJob(config, runtime);
                    tor.Start();
                    interactive.Services.Add(tor);

                    if (!config.OnlyMonitor)
                    {
                        host.Start();
                        interactive.Services.Add(host);
                    }

                    string baseUri;

                    if (breezeConfig.UseTor)
                    {
                        baseUri = runtime.TorUri.ToString().TrimEnd('/');
                    }
                    else
                    {
                        baseUri = runtime.LocalEndpoint.ToString();
                    }

                    if (!baseUri.StartsWith("http://") && (!baseUri.StartsWith("ctb://")))
                    {
                        baseUri = "http://" + baseUri;
                    }

                    var tempUri = (baseUri + "?h=" + runtime.ClassicTumblerParametersHash).Replace("http:", "ctb:");

                    //The uri.txt is only used in the integration tests as there is no registration service running (no Stratis daemon)
                    File.WriteAllText(Path.Combine(config.DataDir, "uri.txt"), tempUri);

                    interactive.StartInteractive();
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (InterruptedConsoleException) { }
                catch (Exception exception)
                {
                    Logs.Tumbler.LogError("Exception thrown while running the server");
                    Logs.Tumbler.LogError(exception.ToString());
                }
            }
        }
Ejemplo n.º 9
0
        /// <inheritdoc />
        public async Task TumbleAsync(string originWalletName, string destinationWalletName, string originWalletPassword)
        {
            // Make sure it won't start new tumbling round if already started
            if (this.State == TumbleState.Tumbling)
            {
                this.logger.LogDebug("Tumbler is already running");
                throw new Exception("Tumbling is already running");
            }

            this.tumblingState.TumblerUri = new Uri(this.TumblerAddress);

            // Check if in initial block download
            if (!this.chain.IsDownloaded())
            {
                this.logger.LogDebug("Chain is still being downloaded: " + this.chain.Tip);
                throw new Exception("Chain is still being downloaded");
            }

            Wallet destinationWallet = this.walletManager.GetWallet(destinationWalletName);
            Wallet originWallet      = this.walletManager.GetWallet(originWalletName);

            // Check if origin wallet has a balance
            WalletBalanceModel model = new WalletBalanceModel();

            var originWalletAccounts = this.walletManager.GetAccounts(originWallet.Name).ToList();
            var originConfirmed      = new Money(0);
            var originUnconfirmed    = new Money(0);

            foreach (var originAccount in originWallet.GetAccountsByCoinType(this.tumblingState.CoinType))
            {
                var result = originAccount.GetSpendableAmount();

                originConfirmed   += result.ConfirmedAmount;
                originUnconfirmed += result.UnConfirmedAmount;
            }

            // Should ideally take network transaction fee into account too, but that is dynamic
            if ((originConfirmed + originUnconfirmed) <= (this.TumblerParameters.Denomination + this.TumblerParameters.Fee))
            {
                this.logger.LogDebug("Insufficient funds in origin wallet");
                throw new Exception("Insufficient funds in origin wallet");
            }

            // TODO: Check if password is valid before starting any cycles

            // Update the state and save
            this.tumblingState.DestinationWallet     = destinationWallet ?? throw new Exception($"Destination wallet not found. Have you created a wallet with name {destinationWalletName}?");
            this.tumblingState.DestinationWalletName = destinationWalletName;
            this.tumblingState.OriginWallet          = originWallet ?? throw new Exception($"Origin wallet not found. Have you created a wallet with name {originWalletName}?");
            this.tumblingState.OriginWalletName      = originWalletName;
            this.tumblingState.OriginWalletPassword  = originWalletPassword;

            var accounts = this.tumblingState.DestinationWallet.GetAccountsByCoinType(this.tumblingState.CoinType);
            // TODO: Possibly need to preserve destination account name in tumbling state. Default to first account for now
            string accountName = null;

            foreach (var account in accounts)
            {
                if (account.Index == 0)
                {
                    accountName = account.Name;
                }
            }
            var destAccount = this.tumblingState.DestinationWallet.GetAccountByCoinType(accountName, this.tumblingState.CoinType);

            var key     = destAccount.ExtendedPubKey;
            var keyPath = new KeyPath("0");

            // Stop and dispose onlymonitor
            if (this.broadcasterJob != null && this.broadcasterJob.Started)
            {
                await this.broadcasterJob.Stop().ConfigureAwait(false);
            }
            this.runtime?.Dispose();

            // Bypass Tor for integration tests
            FullNodeTumblerClientConfiguration config;

            if (this.TumblerAddress.Contains("127.0.0.1"))
            {
                config = new FullNodeTumblerClientConfiguration(this.tumblingState, onlyMonitor: false,
                                                                connectionTest: false, useProxy: false);
            }
            else
            {
                config = new FullNodeTumblerClientConfiguration(this.tumblingState, onlyMonitor: false,
                                                                connectionTest: false, useProxy: true);
            }

            this.runtime = await TumblerClientRuntime.FromConfigurationAsync(config).ConfigureAwait(false);

            var extPubKey = new BitcoinExtPubKey(key, this.runtime.Network);

            if (key != null)
            {
                this.runtime.DestinationWallet =
                    new ClientDestinationWallet(extPubKey, keyPath, this.runtime.Repository, this.runtime.Network);
            }
            this.TumblerParameters = this.runtime.TumblerParameters;
            // Run onlymonitor mode
            this.broadcasterJob = this.runtime.CreateBroadcasterJob();
            this.broadcasterJob.Start();

            // Run tumbling mode
            this.stateMachine = new StateMachinesExecutor(this.runtime);
            this.stateMachine.Start();

            this.State = TumbleState.Tumbling;

            return;
        }
Ejemplo n.º 10
0
        public void Run(string[] args)
        {
            var argsConf = new TextFileConfiguration(args);
            var debug    = argsConf.GetOrDefault <bool>("debug", false);

            ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();

            bool isTestNet = argsConf.GetOrDefault <bool>("testnet", false);
            bool isRegTest = argsConf.GetOrDefault <bool>("regtest", false);

            string dataDir;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ImpleumNode");
                dataDir = argsConf.GetOrDefault <string>("dataDir", dataDir);
            }
            else
            {
                dataDir = Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".impleumnode");
                dataDir = argsConf.GetOrDefault <string>("dataDir", dataDir);
            }

            string networkRootFolderName = Network.Main.RootFolderName;

            if (isTestNet)
            {
                networkRootFolderName = Network.TestNet.RootFolderName;
            }
            else if (isRegTest)
            {
                networkRootFolderName = Network.RegTest.RootFolderName;
            }

            string logDir = Path.Combine(dataDir, networkRootFolderName, Network.Main.Name, "Logs");

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(debug), false, loggerProcessor)), logDir);

            using (var interactive = new Interactive())
            {
                var config = new TumblerConfiguration();
                config.LoadArgs(args);
                try
                {
                    var runtime = TumblerRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ServerInteractiveRuntime(runtime);
                    StoppableWebHost host = null;
                    if (!config.OnlyMonitor)
                    {
                        host = new StoppableWebHost(() => new WebHostBuilder()
                                                    .UseAppConfiguration(runtime)
                                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                                    .UseStartup <Startup>()
                                                    .Build());
                    }

                    var job = new BroadcasterJob(interactive.Runtime.Services);
                    job.Start();
                    interactive.Services.Add(job);

                    var tor = new TorRegisterJob(config, runtime);
                    tor.Start();
                    interactive.Services.Add(tor);

                    if (!config.OnlyMonitor)
                    {
                        host.Start();
                        interactive.Services.Add(host);
                    }

                    interactive.StartInteractive();
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (InterruptedConsoleException) { }
                catch (Exception exception)
                {
                    Logs.Tumbler.LogError("Exception thrown while running the server");
                    Logs.Tumbler.LogError(exception.ToString());
                }
            }
        }
Ejemplo n.º 11
0
        private static void StartTumbler(string[] args)
        {
            Logs.Configure(new FuncLoggerFactory(i => new ConsoleLogger(i, (a, b) => true, false)));
            CancellationTokenSource broadcasterCancel = new CancellationTokenSource();
            DBreezeRepository       dbreeze           = null;

            try
            {
                var network = args.Contains("-testnet", StringComparer.OrdinalIgnoreCase) ? Network.TestNet :
                              args.Contains("-regtest", StringComparer.OrdinalIgnoreCase) ? Network.RegTest :
                              Network.Main;
                Logs.Configuration.LogInformation("Network: " + network);

                var dataDir     = DefaultDataDirectory.GetDefaultDirectory("NTumbleBit", network);
                var consoleArgs = new TextFileConfiguration(args);
                var configFile  = GetDefaultConfigurationFile(dataDir, network);
                var config      = TextFileConfiguration.Parse(File.ReadAllText(configFile));
                consoleArgs.MergeInto(config, true);
                config.AddAlias("server", "tumbler.server");

                var onlymonitor = config.GetOrDefault <bool>("onlymonitor", false);

                RPCClient rpc = null;
                try
                {
                    rpc = RPCArgs.ConfigureRPCClient(config, network);
                }
                catch
                {
                    throw new ConfigException("Please, fix rpc settings in " + configFile);
                }
                dbreeze = new DBreezeRepository(Path.Combine(dataDir, "db"));

                var services = ExternalServices.CreateFromRPCClient(rpc, dbreeze);

                var broadcaster = new BroadcasterJob(services, Logs.Main);
                broadcaster.Start(broadcasterCancel.Token);
                Logs.Main.LogInformation("BroadcasterJob started");

                if (!onlymonitor)
                {
                    var server = config.GetOrDefault("tumbler.server", null as Uri);
                    if (server == null)
                    {
                        Logs.Main.LogError("tumbler.server not configured");
                        throw new ConfigException();
                    }
                    var client = new TumblerClient(network, server);
                    Logs.Configuration.LogInformation("Downloading tumbler information of " + server.AbsoluteUri);
                    var parameters = Retry(3, () => client.GetTumblerParameters());
                    Logs.Configuration.LogInformation("Tumbler Server Connection successfull");
                    var existingConfig = dbreeze.Get <ClassicTumbler.ClassicTumblerParameters>("Configuration", client.Address.AbsoluteUri);
                    if (existingConfig != null)
                    {
                        if (Serializer.ToString(existingConfig) != Serializer.ToString(parameters))
                        {
                            Logs.Configuration.LogError("The configuration file of the tumbler changed since last connection, it should never happen");
                            throw new ConfigException();
                        }
                    }
                    else
                    {
                        dbreeze.UpdateOrInsert("Configuration", client.Address.AbsoluteUri, parameters, (o, n) => n);
                    }

                    if (parameters.Network != rpc.Network)
                    {
                        throw new ConfigException("The tumbler server run on a different network than the local rpc server");
                    }

                    IDestinationWallet destinationWallet = null;
                    try
                    {
                        destinationWallet = GetDestinationWallet(config, rpc.Network, dbreeze);
                    }
                    catch (Exception ex)
                    {
                        Logs.Main.LogInformation("outputwallet.extpubkey is not configured, trying to use outputwallet.rpc settings.");
                        try
                        {
                            destinationWallet = GetRPCDestinationWallet(config, rpc.Network);
                        }
                        catch { throw ex; }                         //Not a bug, want to throw the other exception
                    }
                    var stateMachine = new StateMachinesExecutor(parameters, client, destinationWallet, services, dbreeze, Logs.Main);
                    stateMachine.Start(broadcasterCancel.Token);
                    Logs.Main.LogInformation("State machines started");
                }
                Logs.Main.LogInformation("Press enter to stop");
                Console.ReadLine();
                broadcasterCancel.Cancel();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            catch (Exception ex)
            {
                Logs.Configuration.LogError(ex.Message);
                Logs.Configuration.LogDebug(ex.StackTrace);
            }
            finally
            {
                if (!broadcasterCancel.IsCancellationRequested)
                {
                    broadcasterCancel.Cancel();
                }
                dbreeze?.Dispose();
            }
        }
Ejemplo n.º 12
0
        public void StartTumbler(bool testnet)
        {
            Logs.Configure(new NTumbleBit.Logging.FuncLoggerFactory(i => new ConsoleLogger(i, (a, b) => true, false)));

            string[] args;

            if (!testnet)
            {
                // TODO: Tumbler is locked to testnet for testing
                args = new string[] { "-testnet" }
            }
            ;
            else
            {
                args = new string[] { "-testnet" }
            };

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false)));

            using (var interactive = new Interactive())
            {
                var config = new TumblerConfiguration();
                config.LoadArgs(args);
                try
                {
                    var runtime = TumblerRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ServerInteractiveRuntime(runtime);
                    IWebHost host = null;
                    if (!config.OnlyMonitor)
                    {
                        host = new WebHostBuilder()
                               .UseKestrel()
                               .UseAppConfiguration(runtime)
                               .UseContentRoot(Directory.GetCurrentDirectory())
                               .UseStartup <Startup>()
                               .UseUrls(config.GetUrls())
                               .Build();
                    }

                    var job = new BroadcasterJob(interactive.Runtime.Services);
                    job.Start(interactive.BroadcasterCancellationToken);

                    if (!config.OnlyMonitor)
                    {
                        new Thread(() =>
                        {
                            try
                            {
                                host.Run(interactive.MixingCancellationToken);
                            }
                            catch (Exception ex)
                            {
                                if (!interactive.MixingCancellationToken.IsCancellationRequested)
                                {
                                    Logs.Tumbler.LogCritical(1, ex, "Error while starting the host");
                                }
                            }
                            if (interactive.MixingCancellationToken.IsCancellationRequested)
                            {
                                Logs.Tumbler.LogInformation("Server stopped");
                            }
                        }).Start();
                    }
                    interactive.StartInteractive();
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (Exception exception)
                {
                    Logs.Tumbler.LogError("Exception thrown while running the server");
                    Logs.Tumbler.LogError(exception.ToString());
                }
            }
        }
    }
Ejemplo n.º 13
0
        public void StartTumbler(bool testnet, bool getConfigOnly)
        {
            string[] args;

            if (!testnet)
            {
                // TODO: Tumbler is locked to testnet for testing
                args = new string[] { "-testnet" }
            }
            ;
            else
            {
                args = new string[] { "-testnet" }
            };

            var argsConf = new TextFileConfiguration(args);
            var debug    = argsConf.GetOrDefault <bool>("debug", false);

            ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(debug), false, loggerProcessor)));

            if (getConfigOnly)
            {
                config = new TumblerConfiguration();
                config.LoadArgs(args);
                runtime = TumblerRuntime.FromConfiguration(config, new AcceptAllClientInteraction());
                return;
            }

            using (var interactive = new Interactive())
            {
                config = new TumblerConfiguration();
                config.LoadArgs(args);
                try
                {
                    runtime             = TumblerRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ServerInteractiveRuntime(runtime);
                    StoppableWebHost host = null;
                    if (!config.OnlyMonitor)
                    {
                        host = new StoppableWebHost(() => new WebHostBuilder()
                                                    .UseAppConfiguration(runtime)
                                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                                    .UseStartup <Startup>()
                                                    .Build());
                    }

                    var job = new BroadcasterJob(interactive.Runtime.Services);
                    job.Start();
                    interactive.Services.Add(job);

                    if (!config.OnlyMonitor)
                    {
                        host.Start();
                        interactive.Services.Add(host);
                    }

                    interactive.StartInteractive();
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (InterruptedConsoleException) { }
                catch (Exception exception)
                {
                    Logs.Tumbler.LogError("Exception thrown while running the server");
                    Logs.Tumbler.LogError(exception.ToString());
                }
            }
        }
    }
Ejemplo n.º 14
0
        public void StartTumbler(BreezeConfiguration breezeConfig, bool getConfigOnly, string ntumblebitServerConf = null, string datadir = null, bool torMandatory = true)
        {
            var argsTemp = new List <string>();

            argsTemp.Add("-debug");

            if (breezeConfig.TumblerNetwork == Network.TestNet)
            {
                argsTemp.Add("-testnet");
            }
            else if (breezeConfig.TumblerNetwork == Network.RegTest)
            {
                argsTemp.Add("-regtest");
            }
            // No else needed, mainnet is defaulted

            if (ntumblebitServerConf != null)
            {
                argsTemp.Add("-conf=" + ntumblebitServerConf);
            }

            if (datadir != null)
            {
                argsTemp.Add("-datadir=" + datadir);
            }

            string[] args     = argsTemp.ToArray();
            var      argsConf = new TextFileConfiguration(args);
            var      debug    = argsConf.GetOrDefault <bool>("debug", false);

            ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(debug), false, loggerProcessor)));

            if (getConfigOnly)
            {
                config = new TumblerConfiguration();
                config.LoadArgs(args);
                runtime = TumblerRuntime.FromConfiguration(config, new AcceptAllClientInteraction());
                return;
            }

            using (var interactive = new Interactive())
            {
                config = new TumblerConfiguration();
                config.LoadArgs(args);

                if (!torMandatory)
                {
                    config.TorMandatory = false;
                }

                try
                {
                    runtime             = TumblerRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ServerInteractiveRuntime(runtime);
                    StoppableWebHost host = null;
                    if (!config.OnlyMonitor)
                    {
                        host = new StoppableWebHost(() => new WebHostBuilder()
                                                    .UseAppConfiguration(runtime)
                                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                                    .UseStartup <Startup>()
                                                    .Build());
                    }

                    var job = new BroadcasterJob(interactive.Runtime.Services);
                    job.Start();
                    interactive.Services.Add(job);

                    var tor = new TorRegisterJob(config, runtime);
                    tor.Start();
                    interactive.Services.Add(tor);

                    if (!config.OnlyMonitor)
                    {
                        host.Start();
                        interactive.Services.Add(host);
                    }

                    string baseUri;

                    if (runtime.TorUri == null)
                    {
                        baseUri = runtime.LocalEndpoint.ToString();
                    }
                    else
                    {
                        if (runtime.TorUri.ToString().EndsWith("/"))
                        {
                            baseUri = runtime.TorUri.ToString().Substring(0, runtime.TorUri.ToString().Length - 1);
                        }
                        else
                        {
                            baseUri = runtime.TorUri.ToString();
                        }
                    }

                    if (!baseUri.StartsWith("http://") && (!baseUri.StartsWith("ctb://")))
                    {
                        baseUri = "http://" + baseUri;
                    }

                    var tempUri = (baseUri + "?h=" + runtime.ClassicTumblerParametersHash).Replace("http:", "ctb:");
                    File.WriteAllText(Path.Combine(config.DataDir, "uri.txt"), tempUri);

                    interactive.StartInteractive();
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (InterruptedConsoleException) { }
                catch (Exception exception)
                {
                    Logs.Tumbler.LogError("Exception thrown while running the server");
                    Logs.Tumbler.LogError(exception.ToString());
                }
            }
        }