public void NotififyAboutMinedBlock(Block block) { var message = new P2PMessage { Chain = new List <Block> { block }, Type = MessageType.BlockMined }; foreach (var peer in Peers) { if (!peer.IsAlive) { peer.Connect(); } peer.Send(message.ToJson()); } }
public async Task HandleMessage(string soketId, WebSocketSharp.WebSocket soket, string message) { var parsedMessage = JsonConvert.DeserializeObject <P2PMessage>(message); if (parsedMessage.Type == MessageType.BlockMined && parsedMessage.Chain.LastOrDefault() != null) { _blockService.AddNewBlock(parsedMessage.Chain.LastOrDefault()); } if (parsedMessage.Type == MessageType.ReplaceChain && parsedMessage.Chain.Count > 0) { _blockService.ReplaceChain(parsedMessage.Chain); } if (parsedMessage.Type == MessageType.GetLastBlock) { var blocks = _blockService.GetBlocks(); var compareLastBlock = new P2PMessage { Type = MessageType.CompareLastBlock, Chain = new List <Block> { blocks.Last() } }; await SendMessage(soketId, soket, compareLastBlock.ToJson()); } if (parsedMessage.Type == MessageType.CompareLastBlock) { var blocks = _blockService.GetBlocks(); var lastIndex = blocks.Last().Index; var anotherLastIndex = parsedMessage.Chain.Last().Index; if (lastIndex != anotherLastIndex) { if (lastIndex > anotherLastIndex) { await SendMessage(soketId, soket, new P2PMessage { Type = MessageType.ReplaceChain, Chain = _blockService.GetBlocks() }.ToJson()); } else { await SendMessage(soketId, soket, new P2PMessage { Type = MessageType.FetchChain }.ToJson()); } } } if (parsedMessage.Type == MessageType.FetchChain) { var compareLastBlock = new P2PMessage() { Type = MessageType.ReplaceChain, Chain = _blockService.GetBlocks() }; await SendMessage(soketId, soket, compareLastBlock.ToJson()); } }