Exemple #1
0
        public async Task OnMessage(WebSocket ws, string message)
        {
            var protocolMessage = message.FromJSON <ProtocolMessage>(new DataContractJsonSerializer());

            _logger.LogDebug($"Message: {message}");

            try
            {
                switch (protocolMessage.Type)
                {
                case MessageType.QUERY_LATEST:
                    await ws.WriteAsync(ProtocolMessage.ResponseLatestMessage(_blockchain.GetLatestBlock()));

                    break;

                case MessageType.QUERY_ALL:
                    await ws.WriteAsync(ProtocolMessage.ResponseChainMessage(_blockchain.Get()));

                    break;

                case MessageType.RESPONSE_BLOCKCHAIN:
                    var reseivedBlocks = protocolMessage.Data;
                    reseivedBlocks.Sort();

                    var lastBlockReceived = reseivedBlocks.Last();
                    var latestBlockHeld   = _blockchain.GetLatestBlock();

                    if (lastBlockReceived.Head > latestBlockHeld.Head)
                    {
                        if (_blockchain.IsValidBlock(lastBlockReceived, latestBlockHeld))
                        {
                            _logger.LogDebug("We can append the received block to our chain");
                            _blockchain.Add(lastBlockReceived);
                            await this.SendMessageToAllAsync(ProtocolMessage.ResponseLatestMessage(_blockchain.GetLatestBlock()).ToJSON(new DataContractJsonSerializer()));
                        }
                        else if (reseivedBlocks.Count == 1)
                        {
                            _logger.LogDebug("We have to query the chain from our peer");
                            await this.SendMessageToAllAsync(ProtocolMessage.QueryAllBlockchainMessage.ToJSON(new DataContractJsonSerializer()));
                        }
                        else
                        {
                            _logger.LogDebug("Received blockchain is longer than current blockchain");
                            _blockchain.ReplaceChain(reseivedBlocks);
                        }
                    }
                    else
                    {
                        _logger.LogDebug("Received blockchain is not longer than received blockchain. Do nothing");
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException($"Unknown MessageType: {protocolMessage.Type}");
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"{e.Message}\r\n{e.StackTrace}");
            }
        }
Exemple #2
0
        static void Main(string[] args)
        {
            //NodeSettings nodeSettings = NodeSettings.FromArguments(args);
            var logger = new LoggerFactory().AddConsole(LogLevel.Trace, false);

            var configuration = new ConfigurationBuilder()
                                //.SetBasePath("")
                                //.AddJsonFile()
                                .AddInMemoryCollection(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("ApplicationName", "blockchain"),
                new KeyValuePair <string, string>("NetworkFeature:ListeningPort", "5555"),
            })
                                .Build();

            var fullNode = new ApplicationBuilder()
                           .UseLoggerFactory(logger)
                           .UseConfiguration(configuration)
                           .Build();

            fullNode.Run();

            return;

            var configuration1 = new ConfigurationBuilder()
                                 //.SetBasePath("")
                                 //.AddJsonFile()
                                 .AddInMemoryCollection(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("ApplicationName", "blockchain"),
                new KeyValuePair <string, string>("WebSocketManager:Listen", "0.0.0.0:9000"),
            })
                                 .Build();

            var node = new ApplicationBuilder()
                       .ConfigureServices(services =>
            {
                var blockChain = new BlockchainService(logger.CreateLogger <BlockchainService>());
                blockChain.Add(blockChain.GenerateNextBlock("test data"));
                services.AddSingleton(blockChain);
            })
                       .UseLoggerFactory(logger)
                       .UseConfiguration(configuration1)
                       .Build();

            node.Start();

            var configuration2 = new ConfigurationBuilder()
                                 .AddInMemoryCollection(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("ApplicationName", "blockchain"),
                new KeyValuePair <string, string>("WebSocketManager:EndPoints", "127.0.0.1:9000"),
                new KeyValuePair <string, string>("WebSocketManager:Listen", "0.0.0.0:9001"),
            })
                                 .Build();

            var node2 = new ApplicationBuilder()
                        .ConfigureServices(services =>
            {
                services.AddSingleton <BlockchainService>(new BlockchainService(logger.CreateLogger <BlockchainService>()));
            })
                        .UseLoggerFactory(logger)
                        .UseConfiguration(configuration2)
                        .Build();



            node2.Start();

            Console.WriteLine("Press any key to stop");
            Console.ReadLine();
            node.Dispose();
            node2.Dispose();
        }