Skip to content

Instantly share code, notes, and snippets.

@FrqSalah
Created January 27, 2024 20:42
Show Gist options
  • Save FrqSalah/decafe60be6ceb886a0ba5a8b54c5f44 to your computer and use it in GitHub Desktop.
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
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