Ejemplo n.º 1
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.º 2
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.º 3
0
        static void Main(string[] args)
        {
            if (args.Length > 0 && args[0] == "run")
            {
                args = args.Skip(1).ToArray(); // Hack to make dotnet watch work
            }
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);

            using var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(loggerProvider);
            var  logger = loggerFactory.CreateLogger("Configuration");
            Logs logs   = new Logs();

            logs.Configure(loggerFactory);
            IConfiguration conf = null;

            try
            {
                conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }

                var builder = new WebHostBuilder()
                              .UseKestrel()
                              .UseConfiguration(conf)
                              .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    if (!conf.GetOrDefault <bool>("verbose", false))
                    {
                        l.AddFilter("Events", LogLevel.Warning);
                    }
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddFilter("Fido2NetLib.DistributedCacheMetadataService", LogLevel.Error);
                    l.AddProvider(new CustomConsoleLogProvider(processor));
                })
                              .UseStartup <Startup>();

                // When we run the app with dotnet run (typically in dev env), the wwwroot isn't in the same directory
                // than this assembly.
                // But when we use dotnet publish, the wwwroot is published alongside the assembly!
                // This fix https://github.com/btcpayserver/btcpayserver/issues/1894
                var defaultContentPath   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var defaultWebRoot       = Path.Combine(defaultContentPath, "wwwroot");
                var defaultWebRootExists = Directory.Exists(defaultWebRoot);
                if (!defaultWebRootExists)
                {
                    // When we use dotnet run...
                    builder.UseContentRoot(Directory.GetCurrentDirectory());
                }
                host = builder.Build();
                host.StartWithTasksAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    // Some tools such as dotnet watch parse this exact log to open the browser
                    logger.LogInformation("Now listening on: " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    logs.Configuration.LogError(ex.Message);
                }
            }
            catch (Exception e) when(PluginManager.IsExceptionByPlugin(e))
            {
                var pluginDir = new DataDirectories().Configure(conf).PluginDir;

                PluginManager.DisablePlugin(pluginDir, e.Source);
            }
            finally
            {
                processor.Dispose();
                if (host == null)
                {
                    logs.Configuration.LogError("Configuration error");
                }
                if (host != null)
                {
                    host.Dispose();
                }
                Serilog.Log.CloseAndFlush();
                loggerProvider.Dispose();
            }
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);

            using var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(loggerProvider);
            var            logger = loggerFactory.CreateLogger("Configuration");
            IConfiguration conf   = null;

            try
            {
                // This is the only way that LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called
                conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }
                Logs.Configure(loggerFactory);
                new BTCPayServerOptions().LoadArgs(conf);
                Logs.Configure(null);
                /////

                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(conf)
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddFilter("Fido2NetLib.DistributedCacheMetadataService", LogLevel.Error);
                    l.AddProvider(new CustomConsoleLogProvider(processor));
                })
                       .UseStartup <Startup>()
                       .Build();
                host.StartWithTasksAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    logger.LogInformation("Listening on " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            catch (Exception e) when(PluginManager.IsExceptionByPlugin(e))
            {
                var pluginDir = new DataDirectories().Configure(conf).PluginDir;

                PluginManager.DisablePlugin(pluginDir, e.Source);
            }
            finally
            {
                processor.Dispose();
                if (host == null)
                {
                    Logs.Configuration.LogError("Configuration error");
                }
                if (host != null)
                {
                    host.Dispose();
                }
                Serilog.Log.CloseAndFlush();
                loggerProvider.Dispose();
            }
        }
Ejemplo n.º 5
0
        public void Run(string[] args)
        {
            var argsConf      = new TextFileConfiguration(args);
            var debug         = argsConf.GetOrDefault <bool>("debug", false);
            var redeemEscrows = argsConf.GetOrDefault <bool>("redeemescrows", false);;

            ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(debug), null, loggerProcessor)));
            using (var interactive = new Interactive())
            {
                try
                {
                    var config = new TumblerClientConfiguration();
                    config.LoadArgs(args);

                    var runtime = TumblerClientRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In));
                    interactive.Runtime = new ClientInteractiveRuntime(runtime);

                    if (redeemEscrows)
                    {
                        RedeemEscrows(runtime).GetAwaiter().GetResult();
                    }


                    var broadcaster = runtime.CreateBroadcasterJob();
                    broadcaster.Start();
                    interactive.Services.Add(broadcaster);
                    //interactive.Services.Add(new CheckIpService(runtime));
                    //interactive.Services.Last().Start();

                    if (!config.OnlyMonitor)
                    {
                        var stateMachine = runtime.CreateStateMachineJob();
                        stateMachine.Start();
                        interactive.Services.Add(stateMachine);
                    }

                    interactive.StartInteractive();
                }
                catch (ClientInteractionException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (ConfigException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Logs.Configuration.LogError(ex.Message);
                    }
                }
                catch (InterruptedConsoleException) { }
                catch (Exception ex)
                {
                    Logs.Configuration.LogError(ex.Message);
                    Logs.Configuration.LogDebug(ex.StackTrace);
                }
            }
        }
Ejemplo n.º 6
0
        public void TestDualClientWithoutTor()
        {
            using (NodeBuilder builder = NodeBuilder.Create(version: "0.15.1"))
            {
                HttpClient client = null;

                var coreNode = builder.CreateNode(false);

                coreNode.ConfigParameters.AddOrReplace("debug", "1");
                coreNode.ConfigParameters.AddOrReplace("printtoconsole", "0");
                coreNode.ConfigParameters.AddOrReplace("prematurewitness", "1");
                coreNode.ConfigParameters.AddOrReplace("walletprematurewitness", "1");
                coreNode.ConfigParameters.AddOrReplace("rpcworkqueue", "100");

                coreNode.Start();

                // Replicate portions of BreezeServer's Program.cs. Maybe refactor it into a class/function in future
                var serviceProvider = new ServiceCollection()
                                      .AddLogging()
                                      .AddSingleton <Breeze.BreezeServer.Services.ITumblerService, Breeze.BreezeServer.Services.TumblerService>()
                                      .BuildServiceProvider();

                serviceProvider
                .GetService <ILoggerFactory>()
                .AddConsole(LogLevel.Debug);

                // Skip the registration code - that can be tested separately

                string   configPath         = Path.Combine(coreNode.DataFolder, "breeze.conf");
                string[] breezeServerConfig =
                {
                    "network=regtest", // Only the network setting is currently used from this file
                    "rpc.user=dummy",
                    "rpc.password=dummy",
                    "rpc.url=http://127.0.0.1:26174/",
                    "breeze.ipv4=127.0.0.1",
                    "breeze.ipv6=2001:0db8:85a3:0000:0000:8a2e:0370:7334",
                    "breeze.onion=0123456789ABCDEF",
                    "breeze.port=37123",
                    "breeze.regtxfeevalue=10000",
                    "breeze.regtxoutputvalue=1000",
                    "tumbler.url=http://127.0.0.1:37123/api/v1/",
                    "tumbler.rsakeyfile=/Users/username/.ntumblebitserver/RegTest/Tumbler.pem",
                    "tumbler.ecdsakeyaddress=TVwRFmEKRCnQAgShf3QshBjp1Tmucm1e87"
                };
                File.WriteAllLines(configPath, breezeServerConfig);

                BreezeConfiguration config = new BreezeConfiguration(configPath);

                var      rpc3 = coreNode.CreateRPCClient();
                string   ntbServerConfigPath = Path.Combine(coreNode.DataFolder, "server.config");
                string[] ntbServerConfig     =
                {
                    "regtest=1",
                    "rpc.url=http://127.0.0.1:" + rpc3.Address.Port + "/",
                    "rpc.user="******"rpc.password="******"cycle=kotori",
                    "tor.enabled=false"
                };

                File.WriteAllLines(ntbServerConfigPath, ntbServerConfig);

                // We need to start up the masternode prior to creating the SBFN instance so that
                // we have the URI available for starting the TumbleBit feature
                // TODO: Also need to see if NTB interactive console interferes with later parts of the test
                new Thread(delegate()
                {
                    Thread.CurrentThread.IsBackground = true;
                    // By instantiating the TumblerService directly the registration logic is skipped
                    var tumbler = serviceProvider.GetService <Breeze.BreezeServer.Services.ITumblerService>();
                    tumbler.StartTumbler(config, false, "server.config", Path.GetFullPath(coreNode.DataFolder), false);
                }).Start();

                // Wait for URI file to be written out by the TumblerService
                while (!File.Exists(Path.Combine(coreNode.DataFolder, "uri.txt")))
                {
                    Thread.Sleep(1000);
                }

                Console.WriteLine("* URI file detected *");
                Thread.Sleep(5000);

                var serverAddress = File.ReadAllText(Path.Combine(coreNode.DataFolder, "uri.txt"));

                // Not used for this test
                ConfigurationOptionWrapper <string> registrationStoreDirectory = new ConfigurationOptionWrapper <string>("RegistrationStoreDirectory", "");

                // Force SBFN to use the temporary hidden service to connect to the server
                ConfigurationOptionWrapper <string> masternodeUri = new ConfigurationOptionWrapper <string>("MasterNodeUri", serverAddress);

                ConfigurationOptionWrapper <string>[] configurationOptions = { registrationStoreDirectory, masternodeUri };

                // Logging for NTB client code
                ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();
                Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(true), false, loggerProcessor)));

                CoreNode node1 = builder.CreateStratisPowNode(false, fullNodeBuilder =>
                {
                    fullNodeBuilder
                    .UseConsensus()
                    .UseBlockStore()
                    .UseMempool()
                    .UseBlockNotification()
                    .UseTransactionNotification()
                    .AddMining()
                    .UseWallet()
                    .UseWatchOnlyWallet()
                    .UseApi()
                    .AddRPC()
                    .UseTumbleBit(configurationOptions);
                });

                node1.ConfigParameters.AddOrReplace("apiuri", "http://localhost:37229");

                CoreNode node2 = builder.CreateStratisPowNode(false, fullNodeBuilder =>
                {
                    fullNodeBuilder
                    .UseConsensus()
                    .UseBlockStore()
                    .UseMempool()
                    .UseBlockNotification()
                    .UseTransactionNotification()
                    .AddMining()
                    .UseWallet()
                    .UseWatchOnlyWallet()
                    .UseApi()
                    .AddRPC()
                    .UseTumbleBit(configurationOptions);
                });

                node2.ConfigParameters.AddOrReplace("apiuri", "http://localhost:37228");

                var apiSettings1 = node1.FullNode.NodeService <ApiSettings>();
                var apiSettings2 = node2.FullNode.NodeService <ApiSettings>();

                node1.Start();
                node2.Start();

                // TODO: See if it is possible to split node1 and node2's logs into separate folders
                NLog.Config.LoggingConfiguration config1 = LogManager.Configuration;
                var folder = Path.Combine(node1.DataFolder, "Logs");

                var tbTarget = new FileTarget();
                tbTarget.Name             = "tumblebit";
                tbTarget.FileName         = Path.Combine(folder, "tumblebit.txt");
                tbTarget.ArchiveFileName  = Path.Combine(folder, "tb-${date:universalTime=true:format=yyyy-MM-dd}.txt");
                tbTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence;
                tbTarget.ArchiveEvery     = FileArchivePeriod.Day;
                tbTarget.MaxArchiveFiles  = 7;
                tbTarget.Layout           = "[${longdate:universalTime=true} ${threadid}${mdlc:item=id}] ${level:uppercase=true}: ${callsite} ${message}";
                tbTarget.Encoding         = Encoding.UTF8;

                var ruleTb = new LoggingRule("*", NLog.LogLevel.Debug, tbTarget);
                config1.LoggingRules.Add(ruleTb);
                config1.AddTarget(tbTarget);

                // Apply new rules.
                LogManager.ReconfigExistingLoggers();

                node1.NotInIBD();
                node2.NotInIBD();

                // Create the source and destination wallets for node 1
                var wm1 = node1.FullNode.NodeService <IWalletManager>() as WalletManager;
                wm1.CreateWallet("TumbleBit1", "alice1");
                wm1.CreateWallet("TumbleBit1", "bob1");

                // Create the source and destination wallets for node 2
                var wm2 = node2.FullNode.NodeService <IWalletManager>() as WalletManager;
                wm2.CreateWallet("TumbleBit1", "alice2");
                wm2.CreateWallet("TumbleBit1", "bob2");

                // Mined coins only mature after 100 blocks on regtest
                // Additionally, we need to force Segwit to activate in order for NTB to work correctly
                coreNode.FindBlock(450);

                var rpc1 = node1.CreateRPCClient();
                var rpc2 = node2.CreateRPCClient();

                rpc3.AddNode(node1.Endpoint, false);
                rpc3.AddNode(node2.Endpoint, false);

                rpc1.AddNode(coreNode.Endpoint, false);
                rpc1.AddNode(node2.Endpoint, false);

                var amount       = new Money(5.0m, MoneyUnit.BTC);
                var destination1 = wm1.GetUnusedAddress(new WalletAccountReference("alice1", "account 0"));
                var destination2 = wm2.GetUnusedAddress(new WalletAccountReference("alice2", "account 0"));

                rpc3.SendToAddress(BitcoinAddress.Create(destination1.Address, Network.RegTest), amount);
                rpc3.SendToAddress(BitcoinAddress.Create(destination2.Address, Network.RegTest), amount);

                Console.WriteLine("Waiting for transactions to propagate and finalise");
                Thread.Sleep(5000);

                coreNode.FindBlock(1);

                // Wait for SBFN to sync with the core node
                TestHelper.WaitLoop(() => rpc1.GetBestBlockHash() == rpc3.GetBestBlockHash());
                TestHelper.WaitLoop(() => rpc2.GetBestBlockHash() == rpc3.GetBestBlockHash());

                // Test implementation note: the coins do not seem to immediately appear in the wallet.
                // This is possibly some sort of race condition between the wallet manager and block generation/sync.
                // This extra delay seems to ensure that the coins are definitely in the wallet by the time the
                // transaction count gets logged to the console below.

                // Wait instead of generating a block
                Thread.Sleep(5000);

                var loggerFactory1 = node1.FullNode.NodeService <ILoggerFactory>();
                var loggerFactory2 = node2.FullNode.NodeService <ILoggerFactory>();

                var logger1 = loggerFactory1.CreateLogger(this.GetType().FullName);
                var logger2 = loggerFactory2.CreateLogger(this.GetType().FullName);

                logger1.LogError("(1) Number of wallet transactions: " + wm1.GetSpendableTransactionsInWallet("alice1").Count());
                logger2.LogError("(2) Number of wallet transactions: " + wm2.GetSpendableTransactionsInWallet("alice2").Count());

                // Connect to server and start tumbling
                using (client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // Sample returned output
                    // {"tumbler":"ctb://<onionaddress>.onion?h=<confighash>","denomination":"0.01000000","fee":"0.00010000","network":"RegTest","estimate":"22200"}
                    var connectResponse = client.GetStringAsync(apiSettings1.ApiUri + "api/TumbleBit/connect").GetAwaiter().GetResult();
                    //Assert.StartsWith("[{\"", connectResponse);
                    var tumbleModel = new TumbleRequest {
                        OriginWalletName = "alice1", OriginWalletPassword = "******", DestinationWalletName = "bob1"
                    };
                    var tumbleContent  = new StringContent(tumbleModel.ToString(), Encoding.UTF8, "application/json");
                    var tumbleResponse = client.PostAsync(apiSettings1.ApiUri + "api/TumbleBit/tumble", tumbleContent).GetAwaiter().GetResult();

                    // Note that the TB client takes about 30 seconds to completely start up, as it has to check the server parameters and
                    // RSA key proofs

                    //Assert.StartsWith("[{\"", tumbleResponse);
                }

                using (client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var connectResponse = client.GetStringAsync(apiSettings2.ApiUri + "api/TumbleBit/connect").GetAwaiter().GetResult();
                    var tumbleModel     = new TumbleRequest {
                        OriginWalletName = "alice2", OriginWalletPassword = "******", DestinationWalletName = "bob2"
                    };
                    var tumbleContent  = new StringContent(tumbleModel.ToString(), Encoding.UTF8, "application/json");
                    var tumbleResponse = client.PostAsync(apiSettings2.ApiUri + "api/TumbleBit/tumble", tumbleContent).GetAwaiter().GetResult();

                    // Note that the TB client takes about 30 seconds to completely start up, as it has to check the server parameters and
                    // RSA key proofs
                }

                logger1.LogError("(1) About to start tumbling loop");
                logger2.LogError("(2) About to start tumbling loop");

                // TODO: Move forward specific numbers of blocks and check interim states? TB tests already do that
                for (int i = 0; i < 80; i++)
                {
                    rpc3.Generate(1);
                    builder.SyncNodes();

                    // Try to ensure the invalid phase error does not occur
                    // (seems to occur when the server has not yet processed a new block and the client has)
                    TestHelper.WaitLoop(() => rpc1.GetBestBlockHash() == rpc3.GetBestBlockHash());
                    TestHelper.WaitLoop(() => rpc2.GetBestBlockHash() == rpc3.GetBestBlockHash());

                    /*var mempool = node1.FullNode.NodeService<MempoolManager>();
                     * var mempoolTx = mempool.GetMempoolAsync().Result;
                     * if (mempoolTx.Count > 0)
                     * {
                     *  Console.WriteLine("--- Mempool contents ---");
                     *  foreach (var tx in mempoolTx)
                     *  {
                     *      var hex = mempool.GetTransaction(tx).Result;
                     *      Console.WriteLine(tx + " ->");
                     *      Console.WriteLine(hex);
                     *      Console.WriteLine("---");
                     *  }
                     * }*/

                    Thread.Sleep(10000);
                }

                // Check destination wallet for tumbled coins

                // TODO: Need to amend TumblerService so that it can be shut down within the test

                if (client != null)
                {
                    client.Dispose();
                    client = null;
                }
            }
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);
            var logger = loggerFactory.CreateLogger("Configuration");

            try
            {
                // This is the only way toat LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called
                var conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }
                Logs.Configure(loggerFactory);
                new BTCPayServerOptions().LoadArgs(conf);
                Logs.Configure(null);
                /////

                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(conf)
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddProvider(new CustomConsoleLogProvider(processor));
                })
                       .UseStartup <Startup>()
                       .Build();
                host.StartAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    logger.LogInformation("Listening on " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            finally
            {
                processor.Dispose();
                if (host == null)
                {
                    Logs.Configuration.LogError("Configuration error");
                }
                if (host != null)
                {
                    host.Dispose();
                }
                loggerProvider.Dispose();
            }
        }
Ejemplo n.º 8
0
        public static void Main(string[] args)
        {
            var processor = new ConsoleLoggerProcessor();

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, null, processor)));
            IWebHost host = null;

            try
            {
                var conf = new DefaultConfiguration()
                {
                    Logger = Logs.Configuration
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }

                // Sanity check of the config, this is not strictly needed as it would happen down the line when the host is built
                // However, a bug in .NET Core fixed in 2.1 will prevent the app from stopping if an exception is thrown by the host
                // at startup. We need to remove this line later
                new ExplorerConfiguration().LoadArgs(conf);

                ConfigurationBuilder builder = new ConfigurationBuilder();
                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseConfiguration(conf)
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.AddFilter("NBXplorer.Authentication.BasicAuthenticationHandler", LogLevel.Critical);
                    if (conf.GetOrDefault <bool>("verbose", false))
                    {
                        l.SetMinimumLevel(LogLevel.Debug);
                    }
                    l.AddProvider(new CustomConsoleLogProvider(processor));
                })
                       .UseStartup <Startup>()
                       .Build();
                host.Run();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            catch (CommandParsingException parsing)
            {
                Logs.Explorer.LogError(parsing.HelpText + "\r\n" + parsing.Message);
            }
            finally
            {
                processor.Dispose();
                if (host != null)
                {
                    host.Dispose();
                }
            }
        }
Ejemplo n.º 9
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.º 10
0
        private const long MAX_DEBUG_LOG_FILE_SIZE = 2000000; // If debug log is in use roll it every N MB.

        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);
            var logger = loggerFactory.CreateLogger("Configuration");

            try
            {
                // This is the only way that LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called
                var conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }
                Logs.Configure(loggerFactory);
                new BTCPayServerOptions().LoadArgs(conf);
                Logs.Configure(null);
                /////

                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(conf)
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddProvider(new CustomConsoleLogProvider(processor));

                    // Use Serilog for debug log file.
                    var debugLogFile = BTCPayServerOptions.GetDebugLog(conf);
                    if (string.IsNullOrEmpty(debugLogFile) != false)
                    {
                        return;
                    }
                    Serilog.Log.Logger = new LoggerConfiguration()
                                         .Enrich.FromLogContext()
                                         .MinimumLevel.Is(BTCPayServerOptions.GetDebugLogLevel(conf))
                                         .WriteTo.File(debugLogFile, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: MAX_DEBUG_LOG_FILE_SIZE, rollOnFileSizeLimit: true, retainedFileCountLimit: 1)
                                         .CreateLogger();

                    l.AddSerilog(Serilog.Log.Logger);
                })
                       .UseStartup <Startup>()
                       .Build();
                host.StartAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    logger.LogInformation("Listening on " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            finally
            {
                processor.Dispose();
                if (host == null)
                {
                    Logs.Configuration.LogError("Configuration error");
                }
                if (host != null)
                {
                    host.Dispose();
                }
                Serilog.Log.CloseAndFlush();
                loggerProvider.Dispose();
            }
        }
 public CustomConsoleLogProvider(ConsoleLoggerProcessor processor)
 {
     _Processor = processor;
 }
Ejemplo n.º 12
0
        internal ConsoleLogger(string name, Func <string, LogLevel, bool> filter, IExternalScopeProvider scopeProvider, ConsoleLoggerProcessor loggerProcessor)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            Name            = name;
            Filter          = filter ?? ((category, logLevel) => true);
            ScopeProvider   = scopeProvider;
            _queueProcessor = loggerProcessor;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Console = new WindowsLogConsole();
            }
            else
            {
                Console = new AnsiLogConsole(new AnsiSystemConsole());
            }
        }
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());
                }
            }
        }
    }
        public CustomConsoleLogger(string name, Func <string, LogLevel, bool> filter, bool includeScopes, ConsoleLoggerProcessor loggerProcessor)
        {
            Name          = name ?? throw new ArgumentNullException(nameof(name));
            Filter        = filter ?? ((category, logLevel) => true);
            IncludeScopes = includeScopes;

            _queueProcessor = loggerProcessor;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Console = new WindowsLogConsole();
            }
            else
            {
                Console = new AnsiLogConsole(new AnsiSystemConsole());
            }
        }
Ejemplo n.º 15
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());
                }
            }
        }