public async Task Can_handle_empty_array_request() { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync("[]", JsonRpcContext.Http); result.Response.Should().BeNull(); result.Responses.Should().NotBeNull(); }
public async Task SendJsonRpcResult(JsonRpcResult result) { string SerializeTimeoutException() { JsonRpcErrorResponse error = _jsonRpcService.GetErrorResponse(ErrorCodes.Timeout, "Request was canceled due to enabled timeout."); return(_jsonSerializer.Serialize(error)); } string resultData; try { resultData = result.IsCollection ? _jsonSerializer.Serialize(result.Responses) : _jsonSerializer.Serialize(result.Response); } catch (Exception e) when(e.InnerException is OperationCanceledException) { resultData = SerializeTimeoutException(); } catch (OperationCanceledException) { resultData = SerializeTimeoutException(); } await SendRawAsync(resultData); }
private void TryPublishEvent(BlockHeader blockHeader, TxReceipt[] receipts, string eventName) { BlockHeader fromBlock = _blockTree.FindHeader(_filter.FromBlock); BlockHeader toBlock = _blockTree.FindHeader(_filter.ToBlock, true); bool isAfterFromBlock = blockHeader.Number >= fromBlock?.Number; bool isBeforeToBlock = blockHeader.Number <= toBlock?.Number; if (isAfterFromBlock && isBeforeToBlock) { var filterLogs = GetFilterLogs(blockHeader, receipts); foreach (var filterLog in filterLogs) { JsonRpcResult result = CreateSubscriptionMessage(filterLog); JsonRpcDuplexClient.SendJsonRpcResult(result); if (_logger.IsTrace) { _logger.Trace($"Logs subscription {Id} printed new log."); } } } else { if (_logger.IsTrace) { _logger.Trace($"Logs subscription {Id}: {eventName} event happens, but there are no logs matching filter."); } } }
public async Task Can_process_batch_request_with_object_params() { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync("[{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"params\":{\"a\":\"0x7f01d9b227593e033bf8d6fc86e634d27aa85568\",\"0x668c24\"}},{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"params\":{\"a\":\"0x7f01d9b227593e033bf8d6fc86e634d27aa85568\",\"0x668c24\"}}]"); result.Response.Should().NotBeNull(); result.Response.Should().BeOfType <JsonRpcErrorResponse>(); }
public async Task Can_handle_empty_object_request() { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync("{}"); result.Response.Should().NotBeNull(); result.Responses.Should().BeNull(); }
public async Task Can_process_batch_request_with_some_params_missing() { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync("[{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"params\":[\"0x7f01d9b227593e033bf8d6fc86e634d27aa85568\",\"0x668c24\"]},{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"params\":[\"0x7f01d9b227593e033bf8d6fc86e634d27aa85568\",\"0x668c24\"]},{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"params\":[\"0x7f01d9b227593e033bf8d6fc86e634d27aa85568\",\"0x668c24\"]},{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\"}]"); result.Responses.Should().NotBeNull(); result.Response.Should().BeNull(); }
private JsonRpcResult GetSyncingSubscriptionResult(bool newHead, SyncingSubscription syncingSubscription, BlockEventArgs blockEventArgs) { JsonRpcResult jsonRpcResult = new JsonRpcResult(); ManualResetEvent manualResetEvent = new ManualResetEvent(false); syncingSubscription.JsonRpcDuplexClient.SendJsonRpcResult(Arg.Do <JsonRpcResult>(j => { jsonRpcResult = j; manualResetEvent.Set(); })); if (newHead) { _blockTree.NewHeadBlock += Raise.EventWith(new object(), blockEventArgs); } else { _blockTree.NewBestSuggestedBlock += Raise.EventWith(new object(), blockEventArgs); } manualResetEvent.WaitOne(TimeSpan.FromMilliseconds(100)); return(jsonRpcResult); }
public async Task Can_handle_value_request() { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync("\"aaa\"", JsonRpcContext.Http); result.Response.Should().NotBeNull(); result.Responses.Should().BeNull(); result.Response.Should().BeSameAs(_errorResponse); }
public void NewPendingTransactionsSubscription_on_NewPending_event_with_null_transaction() { TxEventArgs txEventArgs = new TxEventArgs(null); JsonRpcResult jsonRpcResult = GetNewPendingTransactionsResult(txEventArgs, out _); jsonRpcResult.Response.Should().BeNull(); }
public void NewHeadSubscription_on_NewHeadBlock_event_with_null_block() { BlockEventArgs blockEventArgs = new BlockEventArgs(null); JsonRpcResult jsonRpcResult = GetNewHeadBlockResult(blockEventArgs, out _); jsonRpcResult.Response.Should().BeNull(); }
public async Task Can_handle_null_request() { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync("null"); result.Response.Should().NotBeNull(); result.Responses.Should().BeNull(); result.Response.Should().BeSameAs(_errorResponse); }
private void OnNewPending(object?sender, TxEventArgs e) { ScheduleAction(() => { JsonRpcResult result = CreateSubscriptionMessage(_includeTransactions ? new TransactionForRpc(e.Transaction) : e.Transaction.Hash); JsonRpcDuplexClient.SendJsonRpcResult(result); if (_logger.IsTrace) { _logger.Trace($"NewPendingTransactions subscription {Id} printed hash of NewPendingTransaction."); } }); }
protected JsonRpcResult CreateSubscriptionMessage(object result) { return(JsonRpcResult.Single( new JsonRpcSubscriptionResponse() { Params = new JsonRpcSubscriptionResult() { Result = result, Subscription = Id } }, default)); }
private void OnEvicted(object?sender, TxEventArgs e) { ScheduleAction(() => { JsonRpcResult result = CreateSubscriptionMessage(e.Transaction.Hash); JsonRpcDuplexClient.SendJsonRpcResult(result); if (_logger.IsTrace) { _logger.Trace($"DroppedPendingTransactions subscription {Id} printed hash of DroppedPendingTransaction."); } }); }
private void OnNewReceived(object?sender, UserOperationEventArgs e) { ScheduleAction(() => { JsonRpcResult result = CreateSubscriptionMessage(new { UserOperation = new UserOperationRpc(e.UserOperation), EntryPoint = e.EntryPoint }); JsonRpcDuplexClient.SendJsonRpcResult(result); if (_logger.IsTrace) { _logger.Trace($"newReceivedUserOperations subscription {Id} printed hash of newReceivedUserOperations."); } }); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IJsonRpcProcessor jsonRpcProcessor, IJsonRpcService jsonRpcService) { _jsonSerializer = CreateJsonSerializer(); foreach (JsonConverter converter in jsonRpcService.Converters) { _jsonSerializer.RegisterConverter(converter); } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("Cors"); IConfigProvider configProvider = app.ApplicationServices.GetService <IConfigProvider>(); IInitConfig initConfig = configProvider.GetConfig <IInitConfig>(); IJsonRpcConfig jsonRpcConfig = configProvider.GetConfig <IJsonRpcConfig>(); if (initConfig.WebSocketsEnabled) { app.UseWebSockets(); app.UseWhen(ctx => ctx.WebSockets.IsWebSocketRequest && ctx.Connection.LocalPort == jsonRpcConfig.WebSocketsPort, builder => builder.UseWebSocketsModules()); } app.Use(async(ctx, next) => { if (ctx.Request.Method == "GET") { await ctx.Response.WriteAsync("Nethermind JSON RPC"); } else if (ctx.Connection.LocalPort == jsonRpcConfig.Port && ctx.Request.Method == "POST") { using StreamReader reader = new StreamReader(ctx.Request.Body, Encoding.UTF8); string request = await reader.ReadToEndAsync(); JsonRpcResult result = await jsonRpcProcessor.ProcessAsync(request); if (result.IsCollection) { _jsonSerializer.Serialize(ctx.Response.Body, result.Responses); } else { _jsonSerializer.Serialize(ctx.Response.Body, result.Response); } await ctx.Response.CompleteAsync(); } }); }
public async Task ReceiveAsync(byte[] data) { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync(Encoding.UTF8.GetString(data)); if (result.IsCollection) { await SendRawAsync(_jsonSerializer.Serialize(result.Responses)); } else { await SendRawAsync(_jsonSerializer.Serialize(result.Response)); } }
private void OnBlockAddedToMain(object?sender, BlockReplacementEventArgs e) { ScheduleAction(() => { JsonRpcResult result = CreateSubscriptionMessage(new BlockForRpc(e.Block, _includeTransactions, _specProvider)); JsonRpcDuplexClient.SendJsonRpcResult(result); if (_logger.IsTrace) { _logger.Trace($"NewHeads subscription {Id} printed new block"); } }); }
public void NewHeadSubscription_on_NewHeadBlock_event() { Block block = Build.A.Block.WithDifficulty(1991).WithExtraData(new byte[] { 3, 5, 8 }).TestObject; BlockEventArgs blockEventArgs = new BlockEventArgs(block); JsonRpcResult jsonRpcResult = GetNewHeadBlockResult(blockEventArgs, out var subscriptionId); jsonRpcResult.Response.Should().NotBeNull(); string serialized = _jsonSerializer.Serialize(jsonRpcResult.Response); var expectedResult = string.Concat("{\"jsonrpc\":\"2.0\",\"method\":\"eth_subscription\",\"params\":{\"subscription\":\"", subscriptionId, "\",\"result\":{\"author\":\"0x0000000000000000000000000000000000000000\",\"difficulty\":\"0x7c7\",\"extraData\":\"0x030508\",\"gasLimit\":\"0x3d0900\",\"gasUsed\":\"0x0\",\"hash\":\"0x2e3c1c2a507dc3071a16300858d4e75390e5f43561515481719a1e0dadf22585\",\"logsBloom\":\"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\",\"miner\":\"0x0000000000000000000000000000000000000000\",\"mixHash\":\"0x2ba5557a4c62a513c7e56d1bf13373e0da6bec016755483e91589fe1c6d212e2\",\"nonce\":\"0x00000000000003e8\",\"number\":\"0x0\",\"parentHash\":\"0xff483e972a04a9a62bb4b7d04ae403c615604e4090521ecc5bb7af67f71be09c\",\"receiptsRoot\":\"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\"sha3Uncles\":\"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\"size\":\"0x200\",\"stateRoot\":\"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\"totalDifficulty\":\"0x0\",\"timestamp\":\"0xf4240\",\"transactions\":[],\"transactionsRoot\":\"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\"uncles\":[]}}}"); expectedResult.Should().Be(serialized); }
public void SyncingSubscription_on_NewHeadBlock_event_when_sync_no_change() { SyncingSubscription syncingSubscription = GetSyncingSubscription(10042, 10024); Block blockChanged = Build.A.Block.WithNumber(10030).TestObject; BlockEventArgs blockEventArgs = new BlockEventArgs(blockChanged); _blockTree.Head.Returns(blockChanged); JsonRpcResult jsonRpcResult = GetSyncingSubscriptionResult(true, syncingSubscription, blockEventArgs); jsonRpcResult.Response.Should().BeNull(); }
public void SyncingSubscription_on_NewBestSuggestedBlock_event_when_sync_no_change() { SyncingSubscription syncingSubscription = GetSyncingSubscription(10042, 10024); BlockHeader blockHeader = Build.A.BlockHeader.WithNumber(10045).TestObject; Block block = new Block(blockHeader, BlockBody.Empty); BlockEventArgs blockEventArgs = new BlockEventArgs(block); _blockTree.FindBestSuggestedHeader().Returns(blockHeader); JsonRpcResult jsonRpcResult = GetSyncingSubscriptionResult(false, syncingSubscription, blockEventArgs); jsonRpcResult.Response.Should().BeNull(); }
public async Task Can_process_batch_request_with_nested_array_params() { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync("[{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"params\":[[{\"a\":\"0x7f01d9b227593e033bf8d6fc86e634d27aa85568\",\"b\":\"0x668c24\"}]]},{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"params\":[[{\"a\":\"0x7f01d9b227593e033bf8d6fc86e634d27aa85568\",\"b\":\"0x668c24\"}, 1]]}]"); result.Responses.Should().NotBeNull(); if (_returnErrors) { result.Responses.Should().AllBeOfType <JsonRpcErrorResponse>(); } else { result.Responses.Should().AllBeOfType <JsonRpcSuccessResponse>(); } }
public async Task Can_process_uppercase_params() { JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync("{\"id\":67,\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"Params\":[\"0x7f01d9b227593e033bf8d6fc86e634d27aa85568\",\"0x668c24\"]}"); Assert.AreEqual(67, result.Response.Id); if (_returnErrors) { result.Response.Should().BeOfType <JsonRpcErrorResponse>(); } else { result.Response.Should().BeOfType <JsonRpcSuccessResponse>(); } }
public void NewPendingTransactionsSubscription_on_NewPending_event_with_null_transactions_hash() { Transaction transaction = Build.A.Transaction.TestObject; transaction.Hash = null; TxEventArgs txEventArgs = new TxEventArgs(transaction); JsonRpcResult jsonRpcResult = GetNewPendingTransactionsResult(txEventArgs, out var subscriptionId); jsonRpcResult.Response.Should().NotBeNull(); string serialized = _jsonSerializer.Serialize(jsonRpcResult.Response); var expectedResult = string.Concat("{\"jsonrpc\":\"2.0\",\"method\":\"eth_subscription\",\"params\":{\"subscription\":\"", subscriptionId, "\"}}"); expectedResult.Should().Be(serialized); }
public void JsonRpcResult() { var original = new JsonRpcResult { RequestId = new RequestId(5), Result = new CustomType { Age = 7 }, }; var actual = this.Roundtrip(original); Assert.Equal(original.RequestId, actual.RequestId); Assert.Equal(((CustomType?)original.Result) !.Age, actual.GetResult <CustomType>().Age); }
public void JsonRpcResult() { var original = new JsonRpcResult { Id = 5, Result = new CustomType { Age = 7 }, }; var actual = this.Roundtrip(original); Assert.Equal(original.Id, actual.Id); Assert.Equal(((CustomType)original.Result).Age, ((CustomType)actual.Result).Age); }
public void Resolver_Result() { this.formatter.SetMessagePackSerializerOptions(MessagePackSerializerOptions.Standard.WithResolver(CompositeResolver.Create(new CustomFormatter()))); var originalResultValue = new TypeRequiringCustomFormatter { Prop1 = 3, Prop2 = 5 }; var originalResult = new JsonRpcResult { RequestId = new RequestId(1), Result = originalResultValue, }; var roundtripResult = this.Roundtrip(originalResult); var roundtripResultValue = roundtripResult.GetResult <TypeRequiringCustomFormatter>(); Assert.Equal(originalResultValue.Prop1, roundtripResultValue.Prop1); Assert.Equal(originalResultValue.Prop2, roundtripResultValue.Prop2); }
public void SyncingSubscription_on_NewHeadBlock_event_when_sync_changed_to_true() { SyncingSubscription syncingSubscription = GetSyncingSubscription(10042, 10040); Block blockChanged = Build.A.Block.WithNumber(10024).TestObject; BlockEventArgs blockEventArgs = new BlockEventArgs(blockChanged); _blockTree.Head.Returns(blockChanged); JsonRpcResult jsonRpcResult = GetSyncingSubscriptionResult(true, syncingSubscription, blockEventArgs); jsonRpcResult.Response.Should().NotBeNull(); string serialized = _jsonSerializer.Serialize(jsonRpcResult.Response); var expectedResult = string.Concat("{\"jsonrpc\":\"2.0\",\"method\":\"eth_subscription\",\"params\":{\"subscription\":\"", syncingSubscription.Id, "\",\"result\":{\"isSyncing\":true,\"startingBlock\":\"0x0\",\"currentBlock\":\"0x2728\",\"highestBlock\":\"0x273a\"}}}"); expectedResult.Should().Be(serialized); }
public void SyncingSubscription_on_NewBestSuggestedBlock_event_when_sync_changed_to_false() { SyncingSubscription syncingSubscription = GetSyncingSubscription(10042, 10024); BlockHeader blockHeader = Build.A.BlockHeader.WithNumber(10030).TestObject; Block block = new Block(blockHeader, BlockBody.Empty); BlockEventArgs blockEventArgs = new BlockEventArgs(block); _blockTree.FindBestSuggestedHeader().Returns(blockHeader); JsonRpcResult jsonRpcResult = GetSyncingSubscriptionResult(false, syncingSubscription, blockEventArgs); jsonRpcResult.Response.Should().NotBeNull(); string serialized = _jsonSerializer.Serialize(jsonRpcResult.Response); var expectedResult = string.Concat("{\"jsonrpc\":\"2.0\",\"method\":\"eth_subscription\",\"params\":{\"subscription\":\"", syncingSubscription.Id, "\",\"result\":false}}"); expectedResult.Should().Be(serialized); }
public async Task ReceiveAsync(Memory <byte> data) { Stopwatch stopwatch = Stopwatch.StartNew(); using JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync(Encoding.UTF8.GetString(data.Span), _jsonRpcContext); await SendJsonRpcResult(result); if (result.IsCollection) { _jsonRpcLocalStats.ReportCalls(result.Reports); _jsonRpcLocalStats.ReportCall(new RpcReport("# collection serialization #", stopwatch.ElapsedMicroseconds(), true)); } else { _jsonRpcLocalStats.ReportCall(result.Report, stopwatch.ElapsedMicroseconds()); } }