示例#1
0
        public void TestGenesisEncode()
        {
            Chain chain = new Chain(Genesis.CreateGenesis());

            ChainSerializer serializer = new ChainSerializer();

            var encrypt = serializer.Encode(chain.BlockChain);
            var decrypt = serializer.Decode(serializer.ConcateByteArray(encrypt));

            Assert.AreEqual(((List <Block>)decrypt).Count, chain.BlockChain.Count);
        }
示例#2
0
        public void TestChainEncode()
        {
            IBlockRepository subscriber = new BlockRepository();
            var blocks = subscriber.GetBlocks();

            Chain chain = new Chain(blocks);

            ChainSerializer serializer = new ChainSerializer();
            var             encrypt    = serializer.Encode(chain.BlockChain);
            var             decrypt    = serializer.Decode(serializer.ConcateByteArray(encrypt));

            Assert.AreEqual(((List <Block>)decrypt).Count, chain.BlockChain.Count);
        }
示例#3
0
        private async Task <object> SendChainFromWebSockets(AspNetWebSocketContext context)
        {
            var handler = new BlockChainHandler();

            byte[]          buffer          = new byte[1024 * 1024];
            ChainSerializer chainSerializer = new ChainSerializer();

            var encode_tuple            = chainSerializer.Encode(connector.GetLocalChain().BlockChain);
            ArraySegment <byte> segment =
                new ArraySegment <byte>(chainSerializer.ConcateByteArray(encode_tuple));

            WebSocket socket = context.WebSocket;

            try
            {
                handler.OnOpen();

                WebSocketReceiveResult receiveResult;

                while (socket.State == WebSocketState.Open)
                {
                    do
                    {
                        receiveResult = await socket.ReceiveAsync(
                            segment, CancellationToken.None);

                        if (receiveResult.MessageType == WebSocketMessageType.Close)
                        {
                            await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                        }
                    } while (!receiveResult.EndOfMessage);

                    await socket.SendAsync(segment, WebSocketMessageType.Binary, true, CancellationToken.None);
                }
            }

            catch (Exception ex)
            {
                log.Error("Error when respond blockchain " + ex.Message);
                throw new InvalidBlockException("Error when respond blockchain ");
            }
            finally
            {
                handler.OnClose();
            }

            var processTask = handler.ProcessWebSocketRequestAsync(context);

            return(processTask);
        }
示例#4
0
        public async Task GetBlockChainRequestHandler(AspNetWebSocketContext webSocketContext)
        {
            WebSocket webSocket = webSocketContext.WebSocket;

            ArraySegment <Byte> receiveData = new ArraySegment <Byte>(new Byte[maxMessageSize]);
            var cancelationToken            = new CancellationToken();

            while (webSocket.State == WebSocketState.Open)
            {
                HexString rawBlockChain;

                using (MemoryStream stream = new MemoryStream(maxMessageSize))
                {
                    WebSocketReceiveResult result = await webSocket.ReceiveAsync(receiveData, cancelationToken);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancelationToken);
                    }
                    else
                    {
                        await stream.WriteAsync(receiveData.Array, receiveData.Offset, receiveData.Count);

                        stream.Seek(0, SeekOrigin.Begin);

                        using (BinaryReader reader = new BinaryReader(stream))
                        {
                            rawBlockChain = new HexString(reader.ReadBytes((int)stream.Length));
                        }

                        ChainSerializer serializer = new ChainSerializer();

                        this.GlobalChain = serializer.Decode(rawBlockChain.ToByteArray());
                    }
                }
            }
        }
示例#5
0
        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();
                }
            }
        }