private void ProcessRequest(string line) { try { var rpcContext = new StratumContext(this); // set the context. _packetLogger.Verbose("rx: {0}", line.PrettifyJson()); var async = new JsonRpcStateAsync(_rpcResultHandler, rpcContext) { JsonRpc = line }; JsonRpcProcessor.Process(Pool.Config.Coin.Name, async, rpcContext); } catch (JsonReaderException e) // if client sent an invalid message { _logger.Error("Disconnecting miner {0:l} as we recieved an invalid json-rpc request - {1:l}", Username ?? Connection.RemoteEndPoint.ToString(), e.Message); Connection.Disconnect(); // disconnect him. } }
public void Parse(HttpListenerContext httpContext) { var httpRequest = httpContext.Request; var encoding = Encoding.UTF8; var rpcResultHandler = new AsyncCallback( callback => { var asyncData = ((JsonRpcStateAsync)callback); var result = asyncData.Result; var data = Encoding.UTF8.GetBytes(result); var request = ((HttpRpcResponse)asyncData.AsyncState); request.Response.ContentType = "application/json"; request.Response.ContentEncoding = encoding; request.Response.ContentLength64 = data.Length; request.Response.OutputStream.Write(data, 0, data.Length); }); using (var reader = new StreamReader(httpRequest.InputStream, encoding)) { var line = reader.ReadToEnd(); Log.Verbose(line.PretifyJson()); var response = httpContext.Response; var rpcResponse = new HttpRpcResponse(line, response); var rpcContext = new HttpRpcContext(this, rpcResponse); var async = new JsonRpcStateAsync(rpcResultHandler, rpcResponse) { JsonRpc = line }; JsonRpcProcessor.Process(async, rpcContext); } }
public void Initialize() { IJsonRpcService service = Substitute.For <IJsonRpcService>(); service.SendRequestAsync(Arg.Any <JsonRpcRequest>()).Returns(ci => _returnErrors ? (JsonRpcResponse) new JsonRpcErrorResponse { Id = ci.Arg <JsonRpcRequest>().Id } : new JsonRpcSuccessResponse { Id = ci.Arg <JsonRpcRequest>().Id }); service.GetErrorResponse(0, null).ReturnsForAnyArgs(_errorResponse); service.Converters.Returns(new JsonConverter[] { new AddressConverter() }); // just to test converter loader _fileSystem = Substitute.For <IFileSystem>(); /* we enable recorder always to have an easy smoke test for recording * and this is fine because recorder is non-critical component */ JsonRpcConfig configWithRecorder = new JsonRpcConfig(); configWithRecorder.RpcRecorderEnabled = true; _jsonRpcProcessor = new JsonRpcProcessor(service, new EthereumJsonSerializer(), configWithRecorder, _fileSystem, LimboLogs.Instance); }
/// <summary> /// Called when the WebSocket used in a session receives a message. /// </summary> /// <param name="e">Represents the event data passed to the OnMessage event</param> protected override void OnMessage(MessageEventArgs e) { Serilog.Log.Debug("Processing message"); // Log when the message is Binary. if (e.IsBinary) { Serilog.Log.Verbose("Message Type is Binary"); } Serilog.Log.Verbose($"Message Data: {e.Data}"); // Configure the response behaviour for when the RPC method completes. var asyncState = new JsonRpcStateAsync(ar => { // Get the JSON response from the RPC method. string responseString = ((JsonRpcStateAsync)ar).Result; // There will be no response to send for Notifications. if (!string.IsNullOrWhiteSpace(responseString)) { // Send the JSON response back to the server. Serilog.Log.Verbose($"Sending response: {responseString}"); Send(responseString); } Serilog.Log.Debug("Finished processing message"); }, null); // Set the JSON which represents the RPC method call. asyncState.JsonRpc = e.Data; // Execute the RPC method call asynchronously. JsonRpcProcessor.Process(asyncState); }
protected async Task StartRunners(IConfigProvider configProvider) { IInitConfig initConfig = configProvider.GetConfig <IInitConfig>(); IJsonRpcConfig jsonRpcConfig = configProvider.GetConfig <IJsonRpcConfig>(); var metricsParams = configProvider.GetConfig <IMetricsConfig>(); var logManager = new NLogManager(initConfig.LogFileName, initConfig.LogDirectory); IRpcModuleProvider rpcModuleProvider = jsonRpcConfig.Enabled ? new RpcModuleProvider(configProvider.GetConfig <IJsonRpcConfig>(), logManager) : (IRpcModuleProvider)NullModuleProvider.Instance; var jsonSerializer = new EthereumJsonSerializer(); var webSocketsManager = new WebSocketsManager(); INdmDataPublisher ndmDataPublisher = null; INdmConsumerChannelManager ndmConsumerChannelManager = null; INdmInitializer ndmInitializer = null; var ndmConfig = configProvider.GetConfig <INdmConfig>(); var ndmEnabled = ndmConfig.Enabled; if (ndmEnabled) { ndmDataPublisher = new NdmDataPublisher(); ndmConsumerChannelManager = new NdmConsumerChannelManager(); var initializerName = ndmConfig.InitializerName; if (Logger.IsInfo) { Logger.Info($"NDM initializer: {initializerName}"); } var ndmInitializerType = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .FirstOrDefault(t => t.GetCustomAttribute <NdmInitializerAttribute>()?.Name == initializerName); var ndmModule = new NdmModule(); var ndmConsumersModule = new NdmConsumersModule(); ndmInitializer = new NdmInitializerFactory(ndmInitializerType, ndmModule, ndmConsumersModule, logManager).CreateOrFail(); } var grpcConfig = configProvider.GetConfig <IGrpcConfig>(); GrpcServer grpcServer = null; if (grpcConfig.Enabled) { grpcServer = new GrpcServer(jsonSerializer, logManager); if (ndmEnabled) { ndmConsumerChannelManager.Add(new GrpcNdmConsumerChannel(grpcServer)); } _grpcRunner = new GrpcRunner(grpcServer, grpcConfig, logManager); await _grpcRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during GRPC runner start", x.Exception); } }); } if (initConfig.WebSocketsEnabled) { if (ndmEnabled) { webSocketsManager.AddModule(new NdmWebSocketsModule(ndmConsumerChannelManager, ndmDataPublisher, jsonSerializer)); } } _ethereumRunner = new EthereumRunner(rpcModuleProvider, configProvider, logManager, grpcServer, ndmConsumerChannelManager, ndmDataPublisher, ndmInitializer, webSocketsManager, jsonSerializer); await _ethereumRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during ethereum runner start", x.Exception); } }); if (jsonRpcConfig.Enabled) { rpcModuleProvider.Register(new SingletonModulePool <IWeb3Module>(new Web3Module(logManager))); var jsonRpcService = new JsonRpcService(rpcModuleProvider, logManager); var jsonRpcProcessor = new JsonRpcProcessor(jsonRpcService, jsonSerializer, logManager); if (initConfig.WebSocketsEnabled) { webSocketsManager.AddModule(new JsonRpcWebSocketsModule(jsonRpcProcessor, jsonSerializer)); } Bootstrap.Instance.JsonRpcService = jsonRpcService; Bootstrap.Instance.LogManager = logManager; Bootstrap.Instance.JsonSerializer = jsonSerializer; _jsonRpcRunner = new JsonRpcRunner(configProvider, rpcModuleProvider, logManager, jsonRpcProcessor, webSocketsManager); await _jsonRpcRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during jsonRpc runner start", x.Exception); } }); } else { if (Logger.IsInfo) { Logger.Info("Json RPC is disabled"); } } if (metricsParams.Enabled) { var intervalSeconds = metricsParams.IntervalSeconds; _monitoringService = new MonitoringService(new MetricsUpdater(intervalSeconds), metricsParams.PushGatewayUrl, ClientVersion.Description, metricsParams.NodeName, intervalSeconds, logManager); await _monitoringService.StartAsync().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during starting a monitoring.", x.Exception); } }); } else { if (Logger.IsInfo) { Logger.Info("Monitoring is disabled"); } } }
protected async Task StartRunners(IConfigProvider configProvider) { IInitConfig initConfig = configProvider.GetConfig <IInitConfig>(); IJsonRpcConfig jsonRpcConfig = configProvider.GetConfig <IJsonRpcConfig>(); IMetricsConfig metricsConfig = configProvider.GetConfig <IMetricsConfig>(); NLogManager logManager = new NLogManager(initConfig.LogFileName, initConfig.LogDirectory); IRpcModuleProvider rpcModuleProvider = jsonRpcConfig.Enabled ? new RpcModuleProvider(configProvider.GetConfig <IJsonRpcConfig>(), logManager) : (IRpcModuleProvider)NullModuleProvider.Instance; EthereumJsonSerializer jsonSerializer = new EthereumJsonSerializer(); WebSocketsManager webSocketsManager = new WebSocketsManager(); if (!string.IsNullOrEmpty(metricsConfig.NodeName)) { logManager.SetGlobalVariable("nodeName", metricsConfig.NodeName); } if (metricsConfig.Enabled) { Metrics.Version = VersionToMetrics.ConvertToNumber(ClientVersion.Version); MetricsUpdater metricsUpdater = new MetricsUpdater(metricsConfig); _monitoringService = new MonitoringService(metricsUpdater, metricsConfig, logManager); _monitoringService.RegisterMetrics(typeof(Nethermind.Blockchain.Metrics)); _monitoringService.RegisterMetrics(typeof(Nethermind.Db.Metrics)); _monitoringService.RegisterMetrics(typeof(Nethermind.Evm.Metrics)); _monitoringService.RegisterMetrics(typeof(Nethermind.JsonRpc.Metrics)); _monitoringService.RegisterMetrics(typeof(Nethermind.Trie.Metrics)); _monitoringService.RegisterMetrics(typeof(Nethermind.Network.Metrics)); _monitoringService.RegisterMetrics(typeof(Nethermind.Synchronization.Metrics)); _monitoringService.RegisterMetrics(typeof(Nethermind.TxPool.Metrics)); _monitoringService.RegisterMetrics(typeof(Metrics)); await _monitoringService.StartAsync().ContinueWith(x => { if (x.IsFaulted && (_logger?.IsError ?? false)) { _logger !.Error("Error during starting a monitoring.", x.Exception); } }); } else { if (_logger?.IsInfo ?? false) { _logger !.Info("Grafana / Prometheus metrics are disabled in configuration"); } } IGrpcConfig grpcConfig = configProvider.GetConfig <IGrpcConfig>(); GrpcServer? grpcServer = null; if (grpcConfig.Enabled) { grpcServer = new GrpcServer(jsonSerializer, logManager); _grpcRunner = new GrpcRunner(grpcServer, grpcConfig, logManager); await _grpcRunner.Start().ContinueWith(x => { if (x.IsFaulted && (_logger?.IsError ?? false)) { _logger !.Error("Error during GRPC runner start", x.Exception); } }); } INdmDataPublisher? ndmDataPublisher = null; INdmConsumerChannelManager?ndmConsumerChannelManager = null; INdmInitializer? ndmInitializer = null; INdmConfig ndmConfig = configProvider.GetConfig <INdmConfig>(); bool ndmEnabled = ndmConfig.Enabled; if (ndmEnabled) { ndmDataPublisher = new NdmDataPublisher(); ndmConsumerChannelManager = new NdmConsumerChannelManager(); string initializerName = ndmConfig.InitializerName; if (_logger?.IsInfo ?? false) { _logger !.Info($"NDM initializer: {initializerName}"); } Type ndmInitializerType = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .FirstOrDefault(t => t.GetCustomAttribute <NdmInitializerAttribute>()?.Name == initializerName); NdmModule ndmModule = new NdmModule(); NdmConsumersModule ndmConsumersModule = new NdmConsumersModule(); ndmInitializer = new NdmInitializerFactory(ndmInitializerType, ndmModule, ndmConsumersModule, logManager).CreateOrFail(); if (grpcServer != null) { ndmConsumerChannelManager.Add(new GrpcNdmConsumerChannel(grpcServer)); } webSocketsManager.AddModule(new NdmWebSocketsModule(ndmConsumerChannelManager, ndmDataPublisher, jsonSerializer)); } _ethereumRunner = new EthereumRunner( rpcModuleProvider, configProvider, logManager, grpcServer, ndmConsumerChannelManager, ndmDataPublisher, ndmInitializer, webSocketsManager, jsonSerializer, _monitoringService); await _ethereumRunner.Start().ContinueWith(x => { if (x.IsFaulted && (_logger?.IsError ?? false)) { _logger !.Error("Error during ethereum runner start", x.Exception); } }); if (jsonRpcConfig.Enabled) { rpcModuleProvider.Register(new SingletonModulePool <IWeb3Module>(new Web3Module(logManager), true)); JsonRpcService jsonRpcService = new JsonRpcService(rpcModuleProvider, logManager); JsonRpcProcessor jsonRpcProcessor = new JsonRpcProcessor(jsonRpcService, jsonSerializer, jsonRpcConfig, new FileSystem(), logManager); if (initConfig.WebSocketsEnabled) { webSocketsManager.AddModule(new JsonRpcWebSocketsModule(jsonRpcProcessor, jsonSerializer), true); } Bootstrap.Instance.JsonRpcService = jsonRpcService; Bootstrap.Instance.LogManager = logManager; Bootstrap.Instance.JsonSerializer = jsonSerializer; _jsonRpcRunner = new JsonRpcRunner(configProvider, rpcModuleProvider, logManager, jsonRpcProcessor, webSocketsManager); await _jsonRpcRunner.Start().ContinueWith(x => { if (x.IsFaulted && (_logger?.IsError ?? false)) { _logger !.Error("Error during jsonRpc runner start", x.Exception); } }); } else { if (_logger?.IsInfo ?? false) { _logger !.Info("Json RPC is disabled"); } } }
/// <summary> /// Runs the RPC server, until it receives a call of the "quit" method. /// </summary> public void Run(ADOQueryExecutor executor) { var proxy = new JsonRpcProxy(executor); Config.SetPostProcessHandler((JsonRequest request, JsonResponse response, object context) => { if (response.Error != null) { var innerException = (response.Error.data as Exception); var errorData = new Dictionary <string, string>(); errorData["stacktrace"] = innerException.StackTrace; response.Error = new JsonRpcException(-32603, innerException.Message, errorData); } return(null); }); var listener = new HttpListener(); listener.Prefixes.Add(Endpoint); listener.Start(); try { executor.Open(); while (!proxy.Finished) { var context = listener.GetContext(); AddCORSHeaders(context); if (context.Request.HttpMethod == "OPTIONS") { context.Response.StatusCode = 200; context.Response.StatusDescription = "OK"; context.Response.ContentLength64 = 0; context.Response.OutputStream.Close(); Console.WriteLine("Processing CORS OPTIONS request"); continue; } if (context.Request.HttpMethod != "POST") { context.Response.StatusCode = 405; context.Response.StatusDescription = "Illegal Method"; context.Response.OutputStream.Close(); Console.WriteLine("Invalid request method: {}", context.Request.HttpMethod); continue; } if (context.Request.Url.PathAndQuery != "/") { context.Response.StatusCode = 404; context.Response.StatusDescription = "Not Found"; context.Response.OutputStream.Close(); Console.WriteLine("Invalid request path: {}", context.Request.Url.PathAndQuery); continue; } if (context.Request.ContentType != "application/json") { context.Response.StatusCode = 400; context.Response.StatusDescription = "Illegal Content Type"; context.Response.OutputStream.Close(); Console.WriteLine("Invalid request Content-Type: {}", context.Request.ContentType); continue; } context.Response.ContentType = "application/json"; var inputBuffer = new byte[context.Request.ContentLength64]; var offset = 0L; while (offset != context.Request.ContentLength64) { offset += context.Request.InputStream.Read(inputBuffer, (int)offset, (int)(context.Request.ContentLength64 - offset)); } var input = Encoding.UTF8.GetString(inputBuffer); JsonRpcProcessor .Process(input) .ContinueWith(result => { SetOutputContent(context.Response, result.Result); }) .Wait(); } } catch (Exception) { Console.WriteLine("Terminating web server"); listener.Stop(); executor.Close(); throw; } }
public JsonRpcWebSocketsModule(JsonRpcProcessor jsonRpcProcessor, IJsonSerializer jsonSerializer) { _jsonRpcProcessor = jsonRpcProcessor; _jsonSerializer = jsonSerializer; }
protected async Task StartRunners(IConfigProvider configProvider) { var initParams = configProvider.GetConfig <IInitConfig>(); var metricsParams = configProvider.GetConfig <IMetricsConfig>(); var logManager = new NLogManager(initParams.LogFileName, initParams.LogDirectory); IRpcModuleProvider rpcModuleProvider = initParams.JsonRpcEnabled ? new RpcModuleProvider(configProvider.GetConfig <IJsonRpcConfig>()) : (IRpcModuleProvider)NullModuleProvider.Instance; var webSocketsManager = new WebSocketsManager(); _ethereumRunner = new EthereumRunner(rpcModuleProvider, configProvider, logManager); await _ethereumRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during ethereum runner start", x.Exception); } }); if (initParams.JsonRpcEnabled) { var serializer = new EthereumJsonSerializer(); rpcModuleProvider.Register <IWeb3Module>(new Web3Module(logManager)); var jsonRpcService = new JsonRpcService(rpcModuleProvider, logManager); var jsonRpcProcessor = new JsonRpcProcessor(jsonRpcService, serializer, logManager); webSocketsManager.AddModule(new JsonRpcWebSocketsModule(jsonRpcProcessor, serializer)); Bootstrap.Instance.JsonRpcService = jsonRpcService; Bootstrap.Instance.LogManager = logManager; Bootstrap.Instance.JsonSerializer = serializer; _jsonRpcRunner = new JsonRpcRunner(configProvider, rpcModuleProvider, logManager, jsonRpcProcessor, webSocketsManager); await _jsonRpcRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during jsonRpc runner start", x.Exception); } }); } else { if (Logger.IsInfo) { Logger.Info("Json RPC is disabled"); } } if (metricsParams.MetricsEnabled) { var intervalSeconds = metricsParams.MetricsIntervalSeconds; _monitoringService = new MonitoringService(new MetricsUpdater(intervalSeconds), metricsParams.MetricsPushGatewayUrl, ClientVersion.Description, metricsParams.NodeName, intervalSeconds, logManager); await _monitoringService.StartAsync().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during starting a monitoring.", x.Exception); } }); } else { if (Logger.IsInfo) { Logger.Info("Monitoring is disabled"); } } }
protected async Task StartRunners(IConfigProvider configProvider) { var initParams = configProvider.GetConfig <IInitConfig>(); var metricsParams = configProvider.GetConfig <IMetricsConfig>(); var logManager = new NLogManager(initParams.LogFileName, initParams.LogDirectory); IRpcModuleProvider rpcModuleProvider = initParams.JsonRpcEnabled ? new RpcModuleProvider(configProvider.GetConfig <IJsonRpcConfig>()) : (IRpcModuleProvider)NullModuleProvider.Instance; var webSocketsManager = new WebSocketsManager(); INdmDataPublisher ndmDataPublisher = null; INdmConsumerChannelManager ndmConsumerChannelManager = null; INdmInitializer ndmInitializer = null; var ndmConfig = configProvider.GetConfig <INdmConfig>(); var ndmEnabled = ndmConfig.Enabled; if (ndmEnabled) { ndmDataPublisher = new NdmDataPublisher(); ndmConsumerChannelManager = new NdmConsumerChannelManager(); ndmInitializer = new NdmInitializerFactory(logManager) .CreateOrFail(ndmConfig.InitializerName, ndmConfig.PluginsPath); } var grpcConfig = configProvider.GetConfig <IGrpcConfig>(); GrpcService grpcService = null; if (grpcConfig.Enabled) { grpcService = new GrpcService(logManager); if (ndmEnabled) { ndmConsumerChannelManager.Add(new GrpcNdmConsumerChannel(grpcService)); } _grpcRunner = new GrpcRunner(grpcService, grpcConfig, logManager); await _grpcRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during GRPC runner start", x.Exception); } }); } GrpcClient grpcClient = null; var grpcClientConfig = configProvider.GetConfig <IGrpcClientConfig>(); if (grpcClientConfig.Enabled) { grpcClient = new GrpcClient(grpcClientConfig, new EthereumJsonSerializer(), logManager); _grpcClientRunner = new GrpcClientRunner(grpcClient, grpcClientConfig, logManager); await Task.Factory.StartNew(() => _grpcClientRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during GRPC client runner start", x.Exception); } })); } _ethereumRunner = new EthereumRunner(rpcModuleProvider, configProvider, logManager, grpcService, grpcClient, ndmConsumerChannelManager, ndmDataPublisher, ndmInitializer); await _ethereumRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during ethereum runner start", x.Exception); } }); if (initParams.JsonRpcEnabled) { var serializer = new EthereumJsonSerializer(); rpcModuleProvider.Register <IWeb3Module>(new Web3Module(logManager)); var jsonRpcService = new JsonRpcService(rpcModuleProvider, logManager); var jsonRpcProcessor = new JsonRpcProcessor(jsonRpcService, serializer, logManager); webSocketsManager.AddModule(new JsonRpcWebSocketsModule(jsonRpcProcessor, serializer)); if (ndmEnabled) { webSocketsManager.AddModule(new NdmWebSocketsModule(ndmConsumerChannelManager, ndmDataPublisher)); } Bootstrap.Instance.JsonRpcService = jsonRpcService; Bootstrap.Instance.LogManager = logManager; Bootstrap.Instance.JsonSerializer = serializer; _jsonRpcRunner = new JsonRpcRunner(configProvider, rpcModuleProvider, logManager, jsonRpcProcessor, webSocketsManager); await _jsonRpcRunner.Start().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during jsonRpc runner start", x.Exception); } }); } else { if (Logger.IsInfo) { Logger.Info("Json RPC is disabled"); } } if (metricsParams.MetricsEnabled) { var intervalSeconds = metricsParams.MetricsIntervalSeconds; _monitoringService = new MonitoringService(new MetricsUpdater(intervalSeconds), metricsParams.MetricsPushGatewayUrl, ClientVersion.Description, metricsParams.NodeName, intervalSeconds, logManager); await _monitoringService.StartAsync().ContinueWith(x => { if (x.IsFaulted && Logger.IsError) { Logger.Error("Error during starting a monitoring.", x.Exception); } }); } else { if (Logger.IsInfo) { Logger.Info("Monitoring is disabled"); } } }
public async Task Execute(CancellationToken cancellationToken) { IJsonRpcConfig jsonRpcConfig = _api.Config <IJsonRpcConfig>(); ILogger logger = _api.LogManager.GetClassLogger(); if (jsonRpcConfig.Enabled) { IInitConfig initConfig = _api.Config <IInitConfig>(); JsonRpcLocalStats jsonRpcLocalStats = new JsonRpcLocalStats( _api.Timestamper, jsonRpcConfig, _api.LogManager); JsonRpcService jsonRpcService = new JsonRpcService(_api.RpcModuleProvider, _api.LogManager); JsonRpcProcessor jsonRpcProcessor = new JsonRpcProcessor( jsonRpcService, _api.EthereumJsonSerializer, jsonRpcConfig, _api.FileSystem, _api.LogManager); if (initConfig.WebSocketsEnabled) { // TODO: I do not like passing both service and processor to any of the types JsonRpcWebSocketsModule?webSocketsModule = new JsonRpcWebSocketsModule( jsonRpcProcessor, jsonRpcService, _api.EthereumJsonSerializer, jsonRpcLocalStats); _api.WebSocketsManager !.AddModule(webSocketsModule, true); } Bootstrap.Instance.JsonRpcService = jsonRpcService; Bootstrap.Instance.LogManager = _api.LogManager; Bootstrap.Instance.JsonSerializer = _api.EthereumJsonSerializer; Bootstrap.Instance.JsonRpcLocalStats = jsonRpcLocalStats; var jsonRpcRunner = new JsonRpcRunner( jsonRpcProcessor, _api.WebSocketsManager, _api.ConfigProvider, _api.LogManager, _api); await jsonRpcRunner.Start(cancellationToken).ContinueWith(x => { if (x.IsFaulted && logger.IsError) { logger.Error("Error during jsonRpc runner start", x.Exception); } }); _api.DisposeStack.Push(Disposable.Create(() => jsonRpcRunner.StopAsync())); // do not await } else { if (logger.IsInfo) { logger.Info("Json RPC is disabled"); } } }
static void Main(string[] args) { _svc = new StratumService(); var rpcResultHandler = new AsyncCallback( state => { var async = ((JsonRpcStateAsync)state); var result = async.Result; var writer = ((StreamWriter)async.AsyncState); writer.WriteLine(result); writer.FlushAsync(); }); using (var tcpServer = TcpServer.Create(3333)) { Task.WaitAll( // JSON RPC Server task Task.Run(() => tcpServer.Start((writer, line) => { var async = new JsonRpcStateAsync(rpcResultHandler, writer) { JsonRpc = line }; JsonRpcProcessor.Process(async, writer); })), // Bitcoin client task Task.Run(async() => { var line = ""; var difficulty = 2048; ShowCommands(); while (!String.IsNullOrEmpty(line = Console.ReadLine())) { try { switch (line) { case "n": Console.WriteLine($"Notify new mining job with difficulty {difficulty}."); // set difficulty await NotifyDifficultyAsync(tcpServer, difficulty); await NotifyNewJobAsync(tcpServer); break; case "i": Console.WriteLine($"Increase difficulty. to {difficulty * 2}"); difficulty *= 2; await NotifyDifficultyAsync(tcpServer, difficulty); await NotifyNewJobAsync(tcpServer); break; case "d": Console.WriteLine($"Decrease difficulty. to {difficulty / 2}"); difficulty /= 2; await NotifyDifficultyAsync(tcpServer, difficulty); await NotifyNewJobAsync(tcpServer); break; } } catch (Exception e) { Console.WriteLine(e); } ShowCommands(); } ; }) ); } }
public static Task <string> Invoke(string jsonrpc) { return(JsonRpcProcessor.Process(jsonrpc)); }