Ejemplo n.º 1
0
        public static string TestSerializedRequest <T>(IReadOnlyCollection <JsonConverter> converters, T module, string method, params string[] parameters) where T : class, IModule
        {
            IJsonRpcService        service    = BuildRpcService(module);
            JsonRpcRequest         request    = GetJsonRequest(method, parameters);
            JsonRpcResponse        response   = service.SendRequestAsync(request).Result;
            EthereumJsonSerializer serializer = new EthereumJsonSerializer();

            foreach (JsonConverter converter in converters)
            {
                serializer.RegisterConverter(converter);
            }

            Stream stream = new MemoryStream();

            serializer.Serialize(stream, response);

            // for coverage (and to prove that it does not throw
            Stream indentedStream = new MemoryStream();

            serializer.Serialize(indentedStream, response, true);

            stream.Seek(0, SeekOrigin.Begin);
            string serialized = new StreamReader(stream).ReadToEnd();

            TestContext.Out?.WriteLine("Serialized:");
            TestContext.Out?.WriteLine(serialized);
            return(serialized);
        }
Ejemplo n.º 2
0
        public static JsonRpcResponse TestRequest <T>(T module, string method, params string[] parameters) where T : class, IModule
        {
            IJsonRpcService service = BuildRpcService(module);
            JsonRpcRequest  request = GetJsonRequest(method, parameters);

            return(service.SendRequestAsync(request, JsonRpcContext.Http).Result);
        }
Ejemplo n.º 3
0
        public void Initialize()
        {
            IJsonRpcService service = Substitute.For <IJsonRpcService>();

            service.SendRequestAsync(Arg.Any <JsonRpcRequest>()).Returns(ci => new JsonRpcResponse {
                Id = ci.Arg <JsonRpcRequest>().Id, Result = null, JsonRpc = ci.Arg <JsonRpcRequest>().JsonRpc
            });
            _jsonRpcProcessor = new JsonRpcProcessor(service, new EthereumJsonSerializer(), new JsonRpcConfig(), LimboLogs.Instance);
        }
Ejemplo n.º 4
0
 private JsonRpcResponse TestRequest<T>(T module, string method, params string[] parameters) where T : IRpcModule
 {
     RpcModuleProvider moduleProvider = new RpcModuleProvider(new FileSystem(), _configurationProvider.GetConfig<IJsonRpcConfig>(), LimboLogs.Instance);
     moduleProvider.Register(new SingletonModulePool<T>(new SingletonFactory<T>(module), true));
     _jsonRpcService = new JsonRpcService(moduleProvider, _logManager);
     JsonRpcRequest request = RpcTest.GetJsonRequest(method, parameters);
     JsonRpcResponse response = _jsonRpcService.SendRequestAsync(request, JsonRpcContext.Http).Result;
     Assert.AreEqual(request.Id, response.Id);
     return response;
 }
        private JsonRpcResponse TestRequest <T>(IModule ethModule, string method, params string[] parameters) where T : IModule
        {
            RpcModuleProvider moduleProvider = new RpcModuleProvider(_configurationProvider.GetConfig <IJsonRpcConfig>());

            moduleProvider.Register <T>(ethModule);
            _jsonRpcService = new JsonRpcService(moduleProvider, _logManager);
            JsonRpcRequest  request  = RpcTest.GetJsonRequest(method, parameters);
            JsonRpcResponse response = _jsonRpcService.SendRequestAsync(request).Result;

            Assert.AreEqual(request.Id, response.Id);
            return(response);
        }
Ejemplo n.º 6
0
        public static string TestSerializedRequest <T>(IReadOnlyCollection <JsonConverter> converters, T module, string method, params string[] parameters) where T : class, IModule
        {
            IJsonRpcService        service  = BuildRpcService(module);
            JsonRpcRequest         request  = GetJsonRequest(method, parameters);
            JsonRpcResponse        response = service.SendRequestAsync(request).Result;
            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            settings.Converters       = service.Converters.Union(converters).ToArray();
            string serialized = JsonConvert.SerializeObject(response, settings);

            TestContext.WriteLine(serialized.Replace("\"", "\\\""));
            return(serialized);
        }
Ejemplo n.º 7
0
        public static string TestSerializedRequest <T>(IReadOnlyCollection <JsonConverter> converters, T module, string method, params string[] parameters) where T : class, IModule
        {
            IJsonRpcService service    = BuildRpcService(module);
            JsonRpcRequest  request    = GetJsonRequest(method, parameters);
            JsonRpcResponse response   = service.SendRequestAsync(request).Result;
            var             serializer = new EthereumJsonSerializer();

            foreach (var converter in converters)
            {
                serializer.RegisterConverter(converter);
            }
            var serialized = serializer.Serialize(response);

            TestContext.Out?.WriteLine("Serialized:");
            TestContext.Out?.WriteLine(serialized);
            return(serialized);
        }
Ejemplo n.º 8
0
        public static string TestSerializedRequest <T>(IReadOnlyCollection <JsonConverter> converters, T module, string method, params string[] parameters) where T : class, IRpcModule
        {
            IJsonRpcService service = BuildRpcService(module, converters);
            JsonRpcRequest  request = GetJsonRequest(method, parameters);

            JsonRpcContext context = new JsonRpcContext(RpcEndpoint.Http);

            if (module is IContextAwareRpcModule contextAwareModule &&
                contextAwareModule.Context != null)
            {
                context = contextAwareModule.Context;
            }
            JsonRpcResponse response = service.SendRequestAsync(request, context).Result;

            EthereumJsonSerializer serializer = new();

            foreach (JsonConverter converter in converters)
            {
                serializer.RegisterConverter(converter);
            }

            Stream stream = new MemoryStream();
            long   size   = serializer.Serialize(stream, response);

            // for coverage (and to prove that it does not throw
            Stream indentedStream = new MemoryStream();

            serializer.Serialize(indentedStream, response, true);

            stream.Seek(0, SeekOrigin.Begin);
            string serialized = new StreamReader(stream).ReadToEnd();

            TestContext.Out?.WriteLine("Serialized:");
            TestContext.Out?.WriteLine(serialized);

            size.Should().Be(serialized.Length);

            return(serialized);
        }
Ejemplo n.º 9
0
        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);
        }
Ejemplo n.º 10
0
        public async Task <JsonRpcResult> ProcessAsync(string request)
        {
            if (_logger.IsTrace)
            {
                _logger.Trace($"Received JSON RPC request: {request}");
            }

            (JsonRpcRequest Model, IEnumerable <JsonRpcRequest> Collection)rpcRequest;
            try
            {
                rpcRequest = _jsonSerializer.DeserializeObjectOrArray <JsonRpcRequest>(request);
            }
            catch (Exception ex)
            {
                Metrics.JsonRpcRequestDeserializationFailures++;
                if (_logger.IsError)
                {
                    _logger.Error($"Error during parsing/validation, request: {request}", ex);
                }
                var response = _jsonRpcService.GetErrorResponse(ErrorType.ParseError, "Incorrect message");
                TraceResult(response);
                return(JsonRpcResult.Single(response));
            }

            if (rpcRequest.Model != null)
            {
                Metrics.JsonRpcRequests++;
                var response = await _jsonRpcService.SendRequestAsync(rpcRequest.Model);

                if (response.Error != null)
                {
                    if (_logger.IsError)
                    {
                        _logger.Error($"Failed to respond to {rpcRequest.Model.Method} {response.Error.Message}");
                    }
                    Metrics.JsonRpcErrors++;
                }
                else
                {
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"Responded to {rpcRequest.Model.Method}");
                    }
                    Metrics.JsonRpcSuccesses++;
                }

                TraceResult(response);
                return(JsonRpcResult.Single(response));
            }

            if (rpcRequest.Collection != null)
            {
                var responses = new List <JsonRpcResponse>();
                foreach (var jsonRpcRequest in rpcRequest.Collection)
                {
                    Metrics.JsonRpcRequests++;
                    var response = await _jsonRpcService.SendRequestAsync(jsonRpcRequest);

                    if (response.Error != null)
                    {
                        if (_logger.IsError)
                        {
                            _logger.Error($"Failed to respond to {jsonRpcRequest.Method} {response.Error.Message}");
                        }
                        Metrics.JsonRpcErrors++;
                    }
                    else
                    {
                        if (_logger.IsDebug)
                        {
                            _logger.Debug($"Responded to {jsonRpcRequest.Method}");
                        }
                        Metrics.JsonRpcSuccesses++;
                    }

                    responses.Add(response);
                }

                TraceResult(responses.ToArray());
                return(JsonRpcResult.Collection(responses));
            }

            Metrics.JsonRpcInvalidRequests++;
            var errorResponse = _jsonRpcService.GetErrorResponse(ErrorType.InvalidRequest, "Invalid request");

            TraceResult(errorResponse);
            return(JsonRpcResult.Single(errorResponse));
        }
Ejemplo n.º 11
0
        public async Task <JsonRpcResult> ProcessAsync(string request)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();

            (JsonRpcRequest Model, List <JsonRpcRequest> Collection)rpcRequest;
            try
            {
                rpcRequest = _jsonSerializer.DeserializeObjectOrArray <JsonRpcRequest>(request);
            }
            catch (Exception ex)
            {
                Metrics.JsonRpcRequestDeserializationFailures++;
                if (_logger.IsError)
                {
                    _logger.Error($"Error during parsing/validation, request: {request}", ex);
                }
                JsonRpcResponse response = _jsonRpcService.GetErrorResponse(ErrorType.ParseError, "Incorrect message");
                TraceResult(response);
                return(JsonRpcResult.Single(response));
            }

            if (rpcRequest.Model != null)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"JSON RPC request {rpcRequest.Model.Method}");
                }

                Metrics.JsonRpcRequests++;
                JsonRpcResponse response = await _jsonRpcService.SendRequestAsync(rpcRequest.Model);

                if (response.Error != null)
                {
                    if (_logger.IsError)
                    {
                        _logger.Error($"Failed to respond to {rpcRequest.Model.Method} {response.Error.Message}");
                    }
                    Metrics.JsonRpcErrors++;
                }
                else
                {
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"Responded to {rpcRequest.Model.Method}");
                    }
                    Metrics.JsonRpcSuccesses++;
                }

                TraceResult(response);
                stopwatch.Stop();
                if (_logger.IsDebug)
                {
                    _logger.Debug($"  {rpcRequest.Model.Method} handled in {stopwatch.Elapsed.TotalMilliseconds}ms");
                }
                return(JsonRpcResult.Single(response));
            }

            if (rpcRequest.Collection != null)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"{rpcRequest.Collection.Count} JSON RPC requests");
                }

                var       responses          = new List <JsonRpcResponse>();
                int       requestIndex       = 0;
                Stopwatch singleRequestWatch = new Stopwatch();
                foreach (JsonRpcRequest jsonRpcRequest in rpcRequest.Collection)
                {
                    singleRequestWatch.Start();

                    Metrics.JsonRpcRequests++;
                    JsonRpcResponse response = await _jsonRpcService.SendRequestAsync(jsonRpcRequest);

                    if (response.Error != null)
                    {
                        if (_logger.IsError)
                        {
                            _logger.Error($"Failed to respond to {jsonRpcRequest.Method} {response.Error.Message}");
                        }
                        Metrics.JsonRpcErrors++;
                    }
                    else
                    {
                        if (_logger.IsDebug)
                        {
                            _logger.Debug($"Responded to {jsonRpcRequest.Method}");
                        }
                        Metrics.JsonRpcSuccesses++;
                    }

                    singleRequestWatch.Stop();
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"  {requestIndex++}/{rpcRequest.Collection.Count} JSON RPC request - {jsonRpcRequest.Method} handled after {singleRequestWatch.Elapsed.TotalMilliseconds}");
                    }
                    responses.Add(response);
                }

                TraceResult(responses);
                stopwatch.Stop();
                if (_logger.IsDebug)
                {
                    _logger.Debug($"  {rpcRequest.Collection.Count} requests handled in {stopwatch.Elapsed.TotalMilliseconds}ms");
                }
                return(JsonRpcResult.Collection(responses));
            }

            Metrics.JsonRpcInvalidRequests++;
            JsonRpcResponse errorResponse = _jsonRpcService.GetErrorResponse(ErrorType.InvalidRequest, "Invalid request");

            TraceResult(errorResponse);
            stopwatch.Stop();
            if (_logger.IsDebug)
            {
                _logger.Debug($"  Failed request handled in {stopwatch.Elapsed.TotalMilliseconds}ms");
            }
            return(JsonRpcResult.Single(errorResponse));
        }