public async Task <object> Notify([FromBody] Block block) { var isAccepted = await _blockService.AddBlock(block); return(new { Accepted = isAccepted }); }
private PeerToPeerCommand ResponseBlockchain(PeerToPeerMessage message) { try { var latestBlock = _blockService.GetLatestBlock(); if (message.Data != null && message.Data.Any()) { var orderedData = message.Data.OrderBy(b => Int32.Parse(b.Index)).ToList(); var latestBlockReceived = orderedData[orderedData.Count - 1]; if (latestBlockReceived.GetIndexAsInt() > latestBlock.BlockHeader.GetIndexAsInt()) { _logger.LogDebug("The index of the received latest block is bigger than the local one."); if (latestBlock.BlockHeader.Hash.Equals(latestBlockReceived.PreviousHash)) { _logger.LogDebug("The hash of the latest block is equal to the previous hash of the received block. " + "Adding new block..."); try { _blockService.AddBlock( latestBlockReceived, ObtainBlockContent(message.Graph[message.Graph.Count - 1])); } catch (RdfSerializationException ex) { _logger.LogWarning("Unable to deserialize received graph as Turtle.", ex); } } else if (orderedData.Count == 1) { _logger.LogDebug("The received chain has only one link. Asking for whole chain."); Message returnMessage = new PeerToPeerMessage(MessageType.QUERY_ALL); return(new PeerToPeerCommand(CommandType.BROADCAST, returnMessage)); } else { _logger.LogDebug("Replacing the whole blockchain."); try { _blockService.ReplaceBlockchain(orderedData, ObtainBlockContents(message.Graph)); } catch (RdfSerializationException ex) { _logger.LogDebug("Exception was thrown while serialization RDF graph.", ex); Message returnMessage = new PeerToPeerMessage(MessageType.ERROR); return(new PeerToPeerCommand(CommandType.WRITE_ERROR, returnMessage)); } catch (CreatingBlockException ex) { _logger.LogDebug("Exception was thrown while creating blocks.", ex); Message returnMessage = new PeerToPeerMessage(MessageType.ERROR); return(new PeerToPeerCommand(CommandType.WRITE_ERROR, returnMessage)); } } } else { _logger.LogDebug("The index of the received latest block is not bigger than the local one. Ignoring."); } } } catch (ReadingBlockException ex) { _logger.LogWarning("Exception was thrown while reading block.", ex); } return(new PeerToPeerCommand(CommandType.DO_NOTHING)); }