Created
January 27, 2024 20:42
-
-
Save FrqSalah/decafe60be6ceb886a0ba5a8b54c5f44 to your computer and use it in GitHub Desktop.
Blockchain class, which will contain a list of all the blocks in the blockchain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Blockchain | |
{ | |
public List<Block> Chain { get; set; } | |
public Blockchain() | |
{ | |
Chain = new List<Block> { new Block(0, DateTime.Now, "Genesis Block", "0") }; | |
} | |
public void AddBlock(string data) | |
{ | |
var latestBlock = Chain.Last(); | |
var newBlock = new Block(latestBlock.Index + 1, DateTime.Now, data, latestBlock.Hash); | |
Chain.Add(newBlock); | |
} | |
public bool IsValid() | |
{ | |
for (int i = 1; i < Chain.Count; i++) | |
{ | |
var currentBlock = Chain[i]; | |
var previousBlock = Chain[i - 1]; | |
if (currentBlock.Hash != currentBlock.CalculateHash() || | |
currentBlock.PreviousHash != previousBlock.Hash) | |
{ | |
return false; | |
} | |
} | |
return true; | |
} | |
public Block GetLatestBlock() | |
{ | |
return Chain.Last(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment