Exemplo n.º 1
0
        private static void Benchmark()
        {
            Console.WriteLine("Starting benchmark");
           
            var cnt = 50;
            var iterations = 7;
            for (int iteration = 1; iteration <= iterations; iteration++)
            {
                cnt *= iteration;
                ctr = 0;
                var sw = Stopwatch.StartNew();
                AutoResetEvent are = new AutoResetEvent(false);
                var rpcResultHandler = new AsyncCallback(_ => 
                    {
                        if(Interlocked.Increment(ref ctr) == cnt)
                        {
                            sw.Stop();
                            Console.WriteLine("processed {0} rpc in {1}ms for {2} rpc/sec",cnt,sw.ElapsedMilliseconds, (double)cnt * 1000d / sw.ElapsedMilliseconds);
                            are.Set();
                        }
                    });

                for (int i = 0; i < cnt; i++)
                {
                    var async = new JsonRpcStateAsync(rpcResultHandler, null);
                    async.JsonRpc = "{'method':'add','params':[1,2],'id':1}";
                    JsonRpcProcessor.Process(async);
                }
                are.WaitOne();
            }


            Console.WriteLine("Finished benchmark...");
        }
 public static void Process(JsonRpcStateAsync async, object context = null)
 {
     var t = Task.Factory.StartNew((_async) =>
     {
         var i = (Tuple <JsonRpcStateAsync, object>)_async;
         ProcessJsonRpcState(i.Item1, i.Item2);
     }, new Tuple <JsonRpcStateAsync, object>(async, context));
 }
 public static void Process(string sessionId, JsonRpcStateAsync async, object context = null)
 {
     var t = Task.Factory.StartNew((_async) =>
     {
         var i = (Tuple <string, JsonRpcStateAsync, object>)_async;
         ProcessJsonRpcState(i.Item1, i.Item2, i.Item3);
     }, new Tuple <string, JsonRpcStateAsync, object>(sessionId, async, context));
 }
Exemplo n.º 4
0
 internal static void ProcessJsonRpcState(string sessionId, JsonRpcStateAsync async, object jsonRpcContext = null)
 {
     if (string.IsNullOrEmpty(async.JsonRpc))
     {
         async.JsonRpc = JsonConvert.SerializeObject(async.Request);
     }
     async.Result = ProcessInternal(sessionId, async.JsonRpc, jsonRpcContext);
     async.SetCompleted();
 }
        public static void Process(string sessionId, JsonRpcStateAsync async, object context = null)
        {
            var t = Task.Factory.StartNew((_async) =>
            {
                var i = (Tuple<string, JsonRpcStateAsync, object>)_async;
                ProcessJsonRpcState(i.Item1, i.Item2, i.Item3);
            }, new Tuple<string, JsonRpcStateAsync, object>(sessionId, async, context));

        }
Exemplo n.º 6
0
 public static void Process(string sessionId, JsonRpcStateAsync async, object context = null)
 {
     Process(sessionId, async.JsonRpc, context)
     .ContinueWith(t =>
     {
         async.Result = t.Result;
         async.SetCompleted();
     });
 }
 public static void Process(JsonRpcStateAsync async, object context = null)
 {
     var t = Task.Factory.StartNew((_async) =>
     {
         var i = (Tuple<JsonRpcStateAsync, object>)_async;
         ProcessJsonRpcState(i.Item1,i.Item2);
     }, new Tuple<JsonRpcStateAsync,object>(async,context));
     
 }
Exemplo n.º 8
0
        private static void ConsoleInput()
        {
            var rpcResultHandler = new AsyncCallback(_ => Console.WriteLine(((JsonRpcStateAsync)_).Result));

            for (string line = Console.ReadLine(); !string.IsNullOrEmpty(line); line = Console.ReadLine())
            {
                var async = new JsonRpcStateAsync(rpcResultHandler, null);
                async.JsonRpc = line;
                JsonRpcProcessor.Process(async);
            }
        }
Exemplo n.º 9
0
        public void Parse(ConnectionDataEventArgs e)
        {
            Log.Verbose("RPC-client recv:\n{0}", e.Data.Dump());

            var rpcResultHandler = new AsyncCallback(
                callback =>
                {
                    var asyncData = ((JsonRpcStateAsync)callback);
                    var result = asyncData.Result + "\n"; // quick hack.
                    var client = ((RPCClient)asyncData.AsyncState);
                    var data = Encoding.UTF8.GetBytes(result);
                    Log.Verbose("RPC-client send:\n{0}", data.Dump());
                    client.Connection.Send(data);

                });

            var line = e.Data.ToEncodedString();
            line = line.Replace("\n", ""); // quick hack!

            var async = new JsonRpcStateAsync(rpcResultHandler, this) { JsonRpc = line };
            JsonRpcProcessor.Process(async, this);
        }
Exemplo n.º 10
0
        internal static void ProcessJsonRpcState(string sessionId, JsonRpcStateAsync async, object jsonRpcContext = null)
        {
            var context = async.AsyncState;

            JsonRequest[]  rpcBatch      = null;
            JsonResponse[] responseBatch = null;

            JsonRequest rpc      = null;
            var         handler  = Handler.GetSessionHandler(sessionId);
            var         callback = string.Empty;

            var response = new JsonResponse();

            response.Result = null;
            response.Error  = null;

            string json = async.JsonRpc;

            if (isSingleRpc(json))
            {
                try
                {
                    if (json.Length > 0)
                    {
                        rpc = Newtonsoft.Json.JsonConvert.DeserializeObject <JsonRequest>(json);
                        if (rpc == null)
                        {
                            response.Result = null;
                            response.Id     = null;
                            response.Error  = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."));
                        }
                        else
                        {
                            response.Id = rpc.Id;
                            if (rpc.Method == null)
                            {
                                response.Result = null;
                                response.Id     = rpc.Id;
                                response.Error  = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'"));
                            }
                        }
                    }
                    else
                    {
                        response.Result = null;
                        response.Id     = null;
                        response.Error  = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "The JSON sent is not a valid Request object."));
                    }
                }
                catch (Exception ex)
                {
                    response.Result = null;
                    if (rpc != null)
                    {
                        response.Id = rpc.Id;
                    }
                    response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", ex));
                    var result = Newtonsoft.Json.JsonConvert.SerializeObject(response);
                    async.Result = result;
                    async.SetCompleted();
                    return;
                }

                if (response.Error == null &&
                    rpc != null &&
                    rpc.Method != null)
                {
                    var data = Handler.GetSessionHandler(sessionId).Handle(rpc, jsonRpcContext);
                    if (data != null)
                    {
                        response.Error  = data.Error;
                        response.Result = data.Result;
                        var result = "";
                        if (response.Id != null)    // dont return a result for notifications
                        {
                            result = Newtonsoft.Json.JsonConvert.SerializeObject(response);
                        }
                        async.Result = result;
                        async.SetCompleted();
                        return;
                    }
                }

                var err = Newtonsoft.Json.JsonConvert.SerializeObject(response);

                async.Result = err;
                async.SetCompleted();
            }
            else     // this is a batch of requests
            {
                try
                {
                    rpcBatch      = Newtonsoft.Json.JsonConvert.DeserializeObject <JsonRequest[]>(json);
                    responseBatch = new JsonResponse[rpcBatch.Length];

                    for (int i = 0; i < rpcBatch.Length; i++)
                    {
                        responseBatch[i] = new JsonResponse();
                        if (rpcBatch[i] == null)
                        {
                            responseBatch[i].Result = null;
                            responseBatch[i].Id     = null;
                            responseBatch[i].Error  = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."));
                        }
                        else
                        {
                            responseBatch[i].Id = rpcBatch[i].Id;
                            if (rpcBatch[i].Method == null)
                            {
                                responseBatch[i].Result = null;
                                responseBatch[i].Error  = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'"));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    response.Result = null;
                    if (rpc != null)
                    {
                        response.Id = rpc.Id;
                    }
                    response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", ex));
                    var result = Newtonsoft.Json.JsonConvert.SerializeObject(response);
                    async.Result = result;
                    async.SetCompleted();
                    return;
                }

                // we should have a batch of RPC at this point
                var respBuilder = new StringBuilder();
                for (int i = 0; i < rpcBatch.Length; i++)
                {
                    if (i == 0)
                    {
                        respBuilder.Append("[");
                    }

                    if (rpcBatch[i] == null || rpcBatch[i].Method == null)
                    {
                        responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'"));
                    }
                    else if (responseBatch[i].Error == null)
                    {
                        var data = handler.Handle(rpcBatch[i], jsonRpcContext);
                        if (data != null)
                        {
                            responseBatch[i].Error  = data.Error;
                            responseBatch[i].Result = data.Result;
                        }
                    }
                    // dont return a response for notifications.
                    if (responseBatch[i].Id != null || responseBatch[i].Error != null)
                    {
                        var result = Newtonsoft.Json.JsonConvert.SerializeObject(responseBatch[i]);
                        respBuilder.Append(result);
                        if (i != rpcBatch.Length - 1)
                        {
                            respBuilder.Append(',');
                        }
                    }

                    if (i == rpcBatch.Length - 1)
                    {
                        respBuilder.Append("]");
                        var str = respBuilder.ToString();
                        async.Result = str;
                        async.SetCompleted();     // let IIS think we are completed now.
                        return;
                    }
                }

                // if we made it this far, then there were no items in the array
                response.Id     = null;
                response.Result = null;
                response.Error  = handler.ProcessParseException(json, new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty."));

                var err = Newtonsoft.Json.JsonConvert.SerializeObject(response);

                async.Result = err;
                async.SetCompleted();
            }
        }
Exemplo n.º 11
0
            protected override async Task WorkAction()
            {
                try
                {
                    var context = await this.httpListener.GetContextAsync();

                    var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);
                    var line = await reader.ReadToEndAsync();

                    var async = new JsonRpcStateAsync(RpcResultHandler, context.Response) { JsonRpc = line };
                    JsonRpcProcessor.Process(async, this.rpcServer);
                }
                // ignore the exception if the worker is stopped
                // HttpListenerException will be thrown on SubStop
                catch (HttpListenerException) when (!this.IsStarted) { }
                finally
                {
                    // always notify to continue accepting connections
                    this.NotifyWork();
                }
            }
Exemplo n.º 12
0
            /// <summary>
            /// Main loop of this connection handler, performing request handling as follows:
            /// Receive a JSON-RPC request via the socket connection. Close the connection
            /// in case the current service mode is DISCONNECT_BEFORE_PROCESSING.
            /// Otherwise, forward the request to the interceptor. Either the interceptor
            /// returns a response for that request, or the response is generated by handling 
            /// the request (via the RpcTarget specified at construction time). The response 
            /// is forwarded to the interceptor. In case the current service mode is 
            /// DISCONNECT_BEFORE_REPLY, the connection is closed. Otherwise, the response 
            /// is sent back via the socket to the caller.
            /// </summary>
            public void handleConnection()
            {
                // determine remote socket endpoint
                IPEndPoint remoteEndPoint = ((IPEndPoint)tcpClient.Client.RemoteEndPoint);
                Semaphore sequentialiser = new Semaphore(0, 1);

                try
                {

                    Trace.TraceInformation("handling connection from: " + remoteEndPoint);

                    // default service mode for a new connection is: RELIABLE
                    ManagementService.setServiceMode(remoteEndPoint, ServiceMode.RELIABLE);

                    NetworkStream stream = tcpClient.GetStream();
                    StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false));
                    StreamReader reader = new StreamReader(stream, new UTF8Encoding(false));
                    JsonSerializer jsonSerializer = new JsonSerializer();

                    // main request processing loop
                    while (ContinueConnection)
                    {
                        JsonRequest jsonRequest = (JsonRequest) jsonSerializer.Deserialize(reader, typeof(JsonRequest));

                        if (jsonRequest == null)
                        {
                            Trace.TraceInformation("Connection from host " + remoteEndPoint + " has been closed.");
                            break;
                        }

                        String requestString = JsonConvert.SerializeObject(jsonRequest);

                        // determine current service mode
                        ServiceMode mode = ManagementService.getServiceMode(remoteEndPoint);

                        // in case of RANDOM service behavior, randomly pick how to handle the current request
                        if (mode == ServiceMode.RANDOM)
                        {
                            switch (rnd.Next(3))
                            {
                                case 0:
                                    mode = ServiceMode.RELIABLE;
                                    break;
                                case 1:
                                    mode = ServiceMode.DISCONNECT_BEFORE_PROCESSING;
                                    break;
                                case 2:
                                    mode = ServiceMode.DISCONNECT_BEFORE_REPLY;
                                    break;
                            }
                            Trace.TraceInformation("handling request: " + requestString + " in randomly chosen mode: " + mode);
                        }
                        else
                        {
                            Trace.TraceInformation("handling request: " + requestString + " in mode: " + mode);
                        }

                        // simulate the case where a request is not received (and thus not processed)
                        if (mode == ServiceMode.DISCONNECT_BEFORE_PROCESSING)
                        {
                            Trace.TraceInformation("explicit disconnect before processing request");
                            throw new IOException("explicit disconnect before processing request");
                        }

                        JsonResponse jsonResponse = null;

                        // intercept the request; might return a response to be sent back ...
                        if (interceptor != null)
                            jsonResponse = interceptor.interceptRequest(jsonRequest);

                        // ... or null in case the request shall be processed in the normal way
                        if (jsonResponse == null)
                        {
                            // process the request in the normal way
                            var rpcResultHandler = new AsyncCallback(
                                state =>
                                {
                                    var asyncState = ((JsonRpcStateAsync)state);
                                    var result = asyncState.Result;
                                    var asyncWriter = ((StreamWriter)asyncState.AsyncState);

                                    // create response from result that the handler returned
                                    jsonResponse = JsonConvert.DeserializeObject<JsonResponse>(result);

                                    // signal request handling has finished
                                    sequentialiser.Release();
                                });

                            var async = new JsonRpcStateAsync(rpcResultHandler, writer) { JsonRpc = requestString };
                            JsonRpcProcessor.Process(async, writer);

                            // sequentialise all requests, avoiding any potential conflicts resulting
                            // from concurrent request handling, such as for instance mixing up reply
                            // messages; wait for request to be completed
                            sequentialiser.WaitOne();
                        }

                        // intercept the response (even in case it was a stored response
                        // returned by the request interceptor)
                        if (interceptor != null)
                            interceptor.interceptResponse(jsonRequest, jsonResponse);

                        // simulate the case where the request has been processed, but the
                        // reply could not be sent back
                        if (mode == ServiceMode.DISCONNECT_BEFORE_REPLY)
                        {
                            Trace.TraceInformation("explicit disconnect before sending reply");
                            throw new IOException("explicit disconnect before sending reply");
                        }

                        // send back reply
                        String responseString = JsonConvert.SerializeObject(jsonResponse);

                        writer.Write(responseString);
                        writer.Flush();
                    }
                }
                catch (IOException)
                {
                    Trace.TraceInformation("closing connection with: " + remoteEndPoint);
                }
                catch (Exception e)
                {
                    Trace.TraceError("RPCServer exception " + e);
                }
                finally
                {
                    tcpClient.Close();
                }
            }
Exemplo n.º 13
0
 public static void Process(JsonRpcStateAsync async, object context = null)
 {
     Process(Handler.DefaultSessionId(), async, context);
 }
Exemplo n.º 14
0
        /// <summary>
        /// Parses the incoming data.
        /// </summary>
        /// <param name="e"></param>
        public void Parse(ConnectionDataEventArgs e)
        {
            Log.Verbose("RPC-client recv:\n{0}", e.Data.ToEncodedString());

            var rpcResultHandler = new AsyncCallback(
                callback =>
                {
                    var asyncData = ((JsonRpcStateAsync)callback);
                    var result = asyncData.Result + "\n"; // quick hack.
                    var response = Encoding.UTF8.GetBytes(result);

                    var context = (SocketsRpcContext) asyncData.AsyncState;
                    var miner = (StratumMiner)context.Miner;

                    miner.Connection.Send(response);

                    Log.Verbose("RPC-client send:\n{0}", result);
                });

            var line = e.Data.ToEncodedString();
            line = line.Replace("\n", ""); // quick hack!

            var rpcRequest = new SocketsRpcRequest(line);
            var rpcContext = new SocketsRpcContext(this, rpcRequest);

            var async = new JsonRpcStateAsync(rpcResultHandler, rpcContext) { JsonRpc = line };
            JsonRpcProcessor.Process(async, rpcContext);
        }
Exemplo n.º 15
0
 internal static void ProcessJsonRpcState(string sessionId, JsonRpcStateAsync async, object jsonRpcContext = null)
 {
     async.Result = ProcessInternal(sessionId, async.JsonRpc, jsonRpcContext);
     async.SetCompleted();
 }
Exemplo n.º 16
0
        internal static void ProcessJsonRpcState(string sessionId, JsonRpcStateAsync async, object jsonRpcContext = null)
        {
            var context = async.AsyncState;

            JsonRequest[] rpcBatch = null;
            JsonResponse[] responseBatch = null;

            JsonRequest rpc = null;
            var handler = Handler.GetSessionHandler(sessionId);
            var callback = string.Empty;

            var response = new JsonResponse();

            response.Result = null;
            response.Error = null;

                string json = async.JsonRpc; 
                                
                if (isSingleRpc(json))
                {
                    try
                    {
                        if (json.Length > 0)
                        {
                            rpc = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonRequest>(json);
                            if (rpc == null)
                            {
                                response.Result = null;
                                response.Id = null;
                                response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."));
                            }
                            else
                            {
                                response.Id = rpc.Id;
                                if (rpc.Method == null)
                                {
                                    response.Result = null;
                                    response.Id = rpc.Id;
                                    response.Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'"));
                                }
                            }
                        }
                        else
                        {
                            response.Result = null;
                            response.Id = null;
                            response.Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "The JSON sent is not a valid Request object."));
                        }
                    }
                    catch (Exception ex)
                    {
                        response.Result = null;
                        if (rpc != null) response.Id = rpc.Id;
                        response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", ex));
                        var result = Newtonsoft.Json.JsonConvert.SerializeObject(response);
                        async.Result = result;                        
                        async.SetCompleted();
                        return;
                    }
                    
                    if (response.Error == null
                        && rpc != null
                        && rpc.Method != null)
                    {
                        var data = Handler.GetSessionHandler(sessionId).Handle(rpc, jsonRpcContext);
                        if (data != null)
                        {
                            response.Error = data.Error;
                            response.Result = data.Result;
                            var result = "";
                            if (response.Id != null)// dont return a result for notifications
                            {
                                result=Newtonsoft.Json.JsonConvert.SerializeObject(response);
                            }
                            async.Result = result;
                            async.SetCompleted();
                            return;
                        }
                    }

                    var err = Newtonsoft.Json.JsonConvert.SerializeObject(response);

                    async.Result = err;
                    async.SetCompleted();
                }
                else // this is a batch of requests
                {
                    try
                    {
                        rpcBatch = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonRequest[]>(json);
                        responseBatch = new JsonResponse[rpcBatch.Length];
                        
                        for (int i = 0; i < rpcBatch.Length; i++)
                        {
                            responseBatch[i] = new JsonResponse();
                            if (rpcBatch[i] == null)
                            {
                                responseBatch[i].Result = null;
                                responseBatch[i].Id = null;
                                responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."));
                            }
                            else
                            {
                                responseBatch[i].Id = rpcBatch[i].Id;
                                if (rpcBatch[i].Method == null)
                                {
                                    responseBatch[i].Result = null;
                                    responseBatch[i].Error =handler.ProcessParseException(json,  new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'"));
                                }
                            }
                        }                        
                    }
                    catch (Exception ex)
                    {
                        response.Result = null;
                        if (rpc != null) response.Id = rpc.Id;
                        response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", ex));
                        var result = Newtonsoft.Json.JsonConvert.SerializeObject(response);
                        async.Result = result;
                        async.SetCompleted();
                        return;
                    }

                    // we should have a batch of RPC at this point
                    var respBuilder = new StringBuilder();
                    for (int i = 0; i < rpcBatch.Length; i++)
                    {
                        if (i == 0)
                        {
                            respBuilder.Append("[");
                        }

                        if (rpcBatch[i] == null || rpcBatch[i].Method == null)
                        {
                            responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'"));
                        }
                        else if (responseBatch[i].Error == null)
                        {
                            var data = handler.Handle(rpcBatch[i], jsonRpcContext);
                            if (data != null)
                            {
                                responseBatch[i].Error = data.Error;
                                responseBatch[i].Result = data.Result;
                                                            
                            }
                        }
                        // dont return a response for notifications.
                        if (responseBatch[i].Id != null || responseBatch[i].Error != null)
                        {
                            var result = Newtonsoft.Json.JsonConvert.SerializeObject(responseBatch[i]);
                            respBuilder.Append(result);
                            if (i != rpcBatch.Length - 1)
                            {
                                respBuilder.Append(',');
                            }
                        }

                        if (i == rpcBatch.Length - 1)
                        {
                            respBuilder.Append("]");
                            var str = respBuilder.ToString();
                            async.Result = str;
                            async.SetCompleted(); // let IIS think we are completed now.
                            return;
                        }
                    }

                    // if we made it this far, then there were no items in the array
                    response.Id = null;
                    response.Result = null;
                    response.Error = handler.ProcessParseException(json, new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty."));

                    var err = Newtonsoft.Json.JsonConvert.SerializeObject(response);

                    async.Result = err;
                    async.SetCompleted();
                }     
        }
Exemplo n.º 17
0
        public void Parse(HttpListenerContext httpContext)
        {
            try
            {
                var httpRequest = httpContext.Request;

                using (var reader = new StreamReader(httpRequest.InputStream, Encoding.UTF8))
                {
                    var line = reader.ReadToEnd();
                    var rpcContext = new GetworkContext(this, httpContext);

                    _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("Skipping invalid json-rpc request - {0:l}", e.Message);
            }
        }
Exemplo n.º 18
0
 internal static void ProcessJsonRpcState(string sessionId, JsonRpcStateAsync async, object jsonRpcContext = null)
 {
     async.Result = ProcessInternal(sessionId, async.JsonRpc, jsonRpcContext);
     async.SetCompleted();
 }
Exemplo n.º 19
0
        /// <summary>
        /// Parses the incoming data.
        /// </summary>
        /// <param name="e"></param>
        public void Parse(ConnectionDataEventArgs e)
        {
            _logger.Verbose("rx: {0}", e.Data.ToEncodedString().PrettifyJson());

            var rpcResultHandler = new AsyncCallback(
                callback =>
                {
                    var asyncData = ((JsonRpcStateAsync)callback);
                    var result = asyncData.Result + "\n";
                    var response = Encoding.UTF8.GetBytes(result);

                    var context = (SocketServiceContext) asyncData.AsyncState;

                    var miner = (StratumMiner)context.Miner;
                    miner.Connection.Send(response);

                    _logger.Verbose("tx: {0}", result.PrettifyJson());
                });

            var line = e.Data.ToEncodedString();
            line = line.Replace("\n", "");

            var rpcRequest = new SocketServiceRequest(line);
            var rpcContext = new SocketServiceContext(this, rpcRequest);

            var async = new JsonRpcStateAsync(rpcResultHandler, rpcContext) { JsonRpc = line };
            JsonRpcProcessor.Process(Pool.Config.Coin.Name, async, rpcContext);
        }
Exemplo n.º 20
0
        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);
            }
        }
Exemplo n.º 21
0
 public static void Process(JsonRpcStateAsync async, object context = null,
                            JsonSerializerSettings settings         = null)
 {
     Process(Handler.DefaultSessionId(), async, context, settings);
 }
Exemplo n.º 22
0
 internal static void ProcessJsonRpcState(JsonRpcStateAsync async, object jsonRpcContext = null)
 {
     ProcessJsonRpcState(Handler.DefaultSessionId(), async, jsonRpcContext);
 }
Exemplo n.º 23
0
        public void Parse(HttpListenerContext httpContext)
        {
            var httpRequest = httpContext.Request;

            var rpcResultHandler = new AsyncCallback(
                callback =>
                {
                    var asyncData = ((JsonRpcStateAsync) callback);
                    var result = asyncData.Result;
                    var response = Encoding.UTF8.GetBytes(result);

                    var context = (HttpServiceContext)asyncData.AsyncState;

                    context.Request.Response.ContentType = "application/json";
                    context.Request.Response.ContentEncoding = Encoding.UTF8;
                    context.Request.Response.ContentLength64 = response.Length;
                    context.Request.Response.OutputStream.Write(response, 0, response.Length);
                });

            using (var reader = new StreamReader(httpRequest.InputStream, Encoding.UTF8))
            {
                var line = reader.ReadToEnd();

                Log.ForContext<VanillaMiner>().Verbose(line.PrettifyJson());

                var rpcRequest = new HttpServiceRequest(line, httpContext);
                var rpcContext = new HttpServiceContext(this, rpcRequest);

                var async = new JsonRpcStateAsync(rpcResultHandler, rpcContext) { JsonRpc = line };
                JsonRpcProcessor.Process(async, rpcContext);
            }
        }
Exemplo n.º 24
0
        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.
            }
        }
Exemplo n.º 25
0
 internal static void ProcessJsonRpcState(JsonRpcStateAsync async, object jsonRpcContext = null)
 {
     ProcessJsonRpcState(Handler.DefaultSessionId(), async, jsonRpcContext);
 }