public async Task <IActionResult> Mine() { var proof = await _blockchain.ProofOfWorkAsync(_blockchain.LastBlock.Proof); await _blockchain.AddTransactionAsync(new Transaction { Sender = "0", Recipient = _settings.NodeIdentifier, Amount = 1 }); var block = await _blockchain.AddBlockAsync(proof, Blockchain.HashBlock(_blockchain.LastBlock)); return(Ok(block)); }
public async Task <IActionResult> Mine(string rewardAddress) { try { var newBlock = await _miner.MineAsync(rewardAddress); var block = await _blockchain.AddBlockAsync(newBlock); return(Created($"blockchain/blocks/{block.Index}", block)); } catch (Exception ex) { if (ex is BlockAssertionException && ex.Message.StartsWith("Invalid index")) { return(StatusCode((int)HttpStatusCode.Conflict, "A new block was added before we were able to mine one")); } throw; } }
public async Task <bool?> CheckReceivedBlocksAsync(params Block[] blocks) { var receivedBlocks = blocks.OrderBy(x => x.Index).ToList(); var latestBlockReceived = receivedBlocks[receivedBlocks.Count - 1]; var latestBlockHeld = await _blockchain.GetLastBlockAsync(); // If the received blockchain is not longer than blockchain. Do nothing. if (latestBlockReceived.Index <= latestBlockHeld.Index) { _logger?.LogInformation($"Received blockchain is not longer than blockchain. Do nothing."); return(false); } _logger?.LogInformation($"Blockchain possibly behind. We got: {latestBlockHeld.Index}, Peer got: {latestBlockReceived.Index}"); if (latestBlockHeld.Hash == latestBlockReceived.PreviousHash) { // We can append the received block to our chain _logger?.LogInformation("Appending received block to our chain"); await _blockchain.AddBlockAsync(latestBlockReceived); return(true); } if (receivedBlocks.Count == 1) { // We have to query the chain from our peer _logger?.LogInformation("Querying chain from our peers"); Broadcast(async node => await GetBlocksAsync(node)); return(null); } // Received blockchain is longer than current blockchain _logger?.LogInformation("Received blockchain is longer than current blockchain"); await _blockchain.ReplaceChainAsync(receivedBlocks); return(true); }