public HttpResponseMessage Save([FromBody] Block block) { try { var resultCode = HttpStatusCode.Forbidden; if (block == null) { Request.CreateErrorResponse(resultCode, "Could not read data from body"); } var isValidTransaction = block != null && KeyServices.VerifySignature(block.ReceiptPositions, block.PublicKey, block.Signature); if (isValidTransaction) { //TODO: перенести логику проверки хеша в BLL if (StringUtil.IsBlockValid(block)) { _blockRepository.AddBlock(block); resultCode = HttpStatusCode.OK; } } var response = new HttpResponseMessage { StatusCode = resultCode, Content = new StringContent(JsonConvert.SerializeObject(block), Encoding.UTF8, "application/json") }; return(response); } catch (Exception ex) { var response = new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(ex.Message, Encoding.UTF8, "application/json") }; return(response); } }
private async void ProccessRequest(HttpListenerContext httpListenerContext) { WebSocketContext webSocketContext = null; string ipAddress; try { webSocketContext = await httpListenerContext.AcceptWebSocketAsync(subProtocol : null); ipAddress = httpListenerContext.Request.RemoteEndPoint.ToString(); } catch (Exception) { httpListenerContext.Response.StatusCode = 500; httpListenerContext.Response.Close(); return; } WebSocket webSocket = webSocketContext.WebSocket; try { byte[] receiveBuffer = new byte[256]; ChainSerializer chainSerializer = new ChainSerializer(); IEnumerable <Block> blocks; BlockRepository subscriber = new BlockRepository(); ArraySegment <byte> segment = new ArraySegment <byte>(receiveBuffer); byte[] block = new byte[256]; while (true) { using (MemoryStream stream = new MemoryStream()) { WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync( segment, CancellationToken.None); if (receiveResult.MessageType == WebSocketMessageType.Close) { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); } else { await stream.WriteAsync(segment.Array, segment.Offset, segment.Count); stream.Seek(0, SeekOrigin.Begin); do { using (BinaryReader reader = new BinaryReader(stream)) { block = reader.ReadBytes((int)stream.Length); } } while (!receiveResult.EndOfMessage); blocks = chainSerializer.Decode(block); if (blocks.Count() > 0) { var block_list = blocks.ToList(); var localBlocks = subscriber.GetBlocks(); if (localBlocks.Any(b => b.Hash == block_list[0].Hash)) { return; } else { subscriber.AddBlock(block_list[0]); } } } } } } catch (Exception ex) { log.Error("Error when adding block, reason: " + ex.Message); httpListenerContext.Response.StatusCode = 500; // httpListenerContext.Response.Close(); return; } finally { if (webSocket != null) { webSocket.Dispose(); } } }