Beispiel #1
0
        static void Main(string[] args)
        {
            ThreadPool.SetMinThreads(65535, 65535);
            var server = new JsonRpcServer();

            var client = new JsonRpcClient();

            if (args.Contains("-debug"))
            {
                Logger.DebugMode = true;
                Logger.UseDefaultWriter();
            }

            if (args.Contains("-benchmark"))
            {
                var engine = new JsonRpcInProcessEngine();
                server.UseEngine(engine);
                client.UseEngine(engine);
                server.Start();
                var statisticsList = new List <int>();
                for (var i = 0; i < 20; i++)
                {
                    statisticsList.Add(Benchmark(client, TestData));
                    Console.WriteLine();
                }
                Console.WriteLine();
                Console.WriteLine($"Best: {statisticsList.Max()} rpc/sec, \t Average: {(int)statisticsList.Average()} rpc/sec, \t Worst: {statisticsList.Min()} rpc/sec");
            }
            else
            {
                IJsonRpcServerEngine serverEngine;
                if (args.Contains("-websocket"))
                {
                    serverEngine = new JsonRpcWebSocketServerEngine("http://*:8090/");
                    server.UseEngine(serverEngine);
                }
                else if (args.Contains("-websocket-kestrel"))
                {
                    serverEngine = new JsonRpcKestrelWebSocketServerEngine(IPAddress.Any, 8090);
                    server.UseEngine(serverEngine);
                }
                else
                if (args.Contains("-http-kestrel"))
                {
                    serverEngine = new JsonRpcKestrelHttpServerEngine(IPAddress.Any, 8090);
                    server.UseEngine(serverEngine);
                }
                else
                {
                    serverEngine = new JsonRpcHttpServerEngine("http://*:8090/");
                    server.UseEngine(serverEngine);
                }

                server.Start();
                Console.WriteLine($"JsonRpc Server Started with engine: {serverEngine.Name}.");
            }
            Console.ReadLine();
        }
        public TestRpcClient()
        {
            var glue = new MockService();

            var listener = new JsonRpcServer(glue);

            listener.Register <RpcTargetMock>();
            listener.Start();

            _client = new JsonRpcClient(glue);
        }
Beispiel #3
0
        public void Awake()
        {
            SceneDumpService = new SceneDumpService(new RuntimeObjectWrapperService());

            Processor    = new JsonRpcProcessor();
            QueryService = new SceneQueryService();
            LuaRuntime   = new DefaultUnitiniumLuaRuntime(QueryService);

            Processor.SetMethod("dump", SceneDumpService.DumpScenes);
            Processor.SetMethod("execute", (string script) => LuaRuntime.Execute(script));
            Processor.SetMethod("co_execute", (string script) => LuaRuntime.Execute(script, true));
            Processor.SetMethod("get_execution", (long id) => LuaRuntime.GetExecution((int)id));
            Processor.SetMethod("query", (string query) => QueryService.Execute(query));

            server   = new JsonRpcServer();
            requests = server.Start("http://localhost:" + ListenPort + "/");
        }
Beispiel #4
0
        protected override void OnStart(string[] args)
        {
            ConfigurationForLog();

            if (args == null || args.Length <= 0)
            {
                LogManager.GetCurrentClassLogger().Error("Null parameter.");
                return;
            }

            if (int.TryParse(args[0], out int port) == false)
            {
                LogManager.GetCurrentClassLogger().Error("Invalid parameter. Parameter({0})", args[0]);
                return;
            }

            _rpcServer.Services = AppDomain.CurrentDomain.GetAssemblies()
                                  .SelectMany(s => s.GetTypes())
                                  .Where(p => typeof(JsonRpcService).IsAssignableFrom(p) && p.IsAbstract == false)
                                  .Select(type => (JsonRpcService)Activator.CreateInstance(type)).ToList();

            _rpcServer.Start(port);
        }
Beispiel #5
0
        public void Start(int port)
        {
            _rpcServer.Start(port);

            LogManager.GetCurrentClassLogger().Info("Start {0} services.", _rpcServer.Services.Count);
        }
Beispiel #6
0
        public static async Task InitializeNoWalletAsync()
        {
            WalletService  = null;
            ChaumianClient = null;
            AddressManager = null;
            TorManager     = null;

            #region ConfigInitialization

            Config = new Config(Path.Combine(DataDir, "Config.json"));
            await Config.LoadOrCreateDefaultFileAsync();

            Logger.LogInfo <Config>("Config is successfully initialized.");

            #endregion ConfigInitialization

            BitcoinStore = new BitcoinStore();
            var bstoreInitTask           = BitcoinStore.InitializeAsync(Path.Combine(DataDir, "BitcoinStore"), Network);
            var hwiInitTask              = HwiProcessManager.InitializeAsync(DataDir, Network);
            var addressManagerFolderPath = Path.Combine(DataDir, "AddressManager");
            AddressManagerFilePath = Path.Combine(addressManagerFolderPath, $"AddressManager{Network}.dat");
            var addrManTask = InitializeAddressManagerBehaviorAsync();

            var blocksFolderPath     = Path.Combine(DataDir, $"Blocks{Network}");
            var connectionParameters = new NodeConnectionParameters();

            if (Config.UseTor.Value)
            {
                Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, () => Config.GetCurrentBackendUri(), Config.GetTorSocks5EndPoint());
            }
            else
            {
                Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, Config.GetFallbackBackendUri(), null);
            }

            UpdateChecker = new UpdateChecker(Synchronizer.WasabiClient);

            #region ProcessKillSubscription

            AppDomain.CurrentDomain.ProcessExit += async(s, e) => await TryDesperateDequeueAllCoinsAsync();

            Console.CancelKeyPress += async(s, e) => { e.Cancel = true; await StopAndExitAsync(); };

            #endregion ProcessKillSubscription

            #region TorProcessInitialization

            if (Config.UseTor.Value)
            {
                TorManager = new TorProcessManager(Config.GetTorSocks5EndPoint(), TorLogsFile);
            }
            else
            {
                TorManager = TorProcessManager.Mock();
            }
            TorManager.Start(false, DataDir);

            var fallbackRequestTestUri = new Uri(Config.GetFallbackBackendUri(), "/api/software/versions");
            TorManager.StartMonitor(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(7), DataDir, fallbackRequestTestUri);

            Logger.LogInfo <TorProcessManager>($"{nameof(TorProcessManager)} is initialized.");

            #endregion TorProcessInitialization

            #region MempoolInitialization

            MemPoolService = new MemPoolService();
            connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(MemPoolService));

            #endregion MempoolInitialization

            #region HwiProcessInitialization

            try
            {
                await hwiInitTask;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, nameof(Global));
            }

            #endregion HwiProcessInitialization

            #region BitcoinStoreInitialization

            await bstoreInitTask;

            #endregion BitcoinStoreInitialization

            #region AddressManagerInitialization

            AddressManagerBehavior addressManagerBehavior = await addrManTask;
            connectionParameters.TemplateBehaviors.Add(addressManagerBehavior);

            #endregion AddressManagerInitialization

            #region P2PInitialization

            if (Network == Network.RegTest)
            {
                Nodes = new NodesGroup(Network, requirements: Constants.NodeRequirements);
                try
                {
                    Node node = await Node.ConnectAsync(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));

                    Nodes.ConnectedNodes.Add(node);

                    RegTestMemPoolServingNode = await Node.ConnectAsync(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));

                    RegTestMemPoolServingNode.Behaviors.Add(new MemPoolBehavior(MemPoolService));
                }
                catch (SocketException ex)
                {
                    Logger.LogError(ex, nameof(Global));
                }
            }
            else
            {
                if (Config.UseTor is true)
                {
                    // onlyForOnionHosts: false - Connect to clearnet IPs through Tor, too.
                    connectionParameters.TemplateBehaviors.Add(new SocksSettingsBehavior(Config.GetTorSocks5EndPoint(), onlyForOnionHosts: false, networkCredential: null, streamIsolation: true));
                    // allowOnlyTorEndpoints: true - Connect only to onions and don't connect to clearnet IPs at all.
                    // This of course makes the first setting unneccessary, but it's better if that's around, in case someone wants to tinker here.
                    connectionParameters.EndpointConnector = new DefaultEndpointConnector(allowOnlyTorEndpoints: Network == Network.Main);

                    await AddKnownBitcoinFullNodeAsHiddenServiceAsync(AddressManager);
                }
                Nodes = new NodesGroup(Network, connectionParameters, requirements: Constants.NodeRequirements);

                RegTestMemPoolServingNode = null;
            }

            Nodes.Connect();
            Logger.LogInfo("Start connecting to nodes...");

            if (RegTestMemPoolServingNode != null)
            {
                RegTestMemPoolServingNode.VersionHandshake();
                Logger.LogInfo("Start connecting to mempool serving regtest node...");
            }

            #endregion P2PInitialization

            #region SynchronizerInitialization

            var requestInterval = TimeSpan.FromSeconds(30);
            if (Network == Network.RegTest)
            {
                requestInterval = TimeSpan.FromSeconds(5);
            }

            int maxFiltSyncCount = Network == Network.Main ? 1000 : 10000;             // On testnet, filters are empty, so it's faster to query them together

            Synchronizer.Start(requestInterval, TimeSpan.FromMinutes(5), maxFiltSyncCount);
            Logger.LogInfo("Start synchronizing filters...");

            #endregion SynchronizerInitialization

            #region JsonRpcServerInitialization

            var jsonRpcServerConfig = new JsonRpcServerConfiguration(Config);
            if (jsonRpcServerConfig.IsEnabled)
            {
                RpcServer = new JsonRpcServer(jsonRpcServerConfig);
                RpcServer.Start();
            }

            #endregion JsonRpcServerInitialization

            Initialized = true;
        }
		public async void Ping_does_not_time_out() {
			server.Configurations.PingFrequency = 250;
			server.Configurations.PingTimeoutDisconnectTime = 500;

			server = new JsonRpcServer<TestActionHandler>(server.Configurations);
			server.OnClientConnect += (sender, e) => {

				Task.Run(async () => {
					await Task.Delay(1000);

					if (e.Client.Info.Status == ClientStatus.Connected) {
						CompleteTest();
					} else {
						FailTest();
					}
				});
			};

			server.Start();
			client.Connect();

			await StartAndWaitClient();
		}
		public async void Ping_client_times_out() {
			server.Configurations.PingFrequency = 250;
			server.Configurations.PingTimeoutDisconnectTime = 500;
			server = new JsonRpcServer<TestActionHandler>(server.Configurations);



			server.OnClientConnect += (sender, e) => {

				// Make the remote client ignore all incoming requests.
				e.Client.OnDataReceived += (s2, e2) => {
					e2.Handled = true;
				};
			};

			server.OnClientDisconnect += (sender, e) => {
				CompleteTest();
			};

			server.Start();

			client.Connect();

			await StartAndWaitClient();
		}