Skip to content

Instantly share code, notes, and snippets.

@Theoistic
Last active August 31, 2022 00:56
Show Gist options
  • Save Theoistic/bec428b5b2ad7ef84efb2d2551af6809 to your computer and use it in GitHub Desktop.
Save Theoistic/bec428b5b2ad7ef84efb2d2551af6809 to your computer and use it in GitHub Desktop.
Over simplified Blockchain
if(System.Environment.GetCommandLineArgs().Length == 0) {
Console.Write("Add something to the blockchain:\n> ");
AddBlock(Console.ReadLine());
} else {
switch (System.Environment.GetCommandLineArgs()[0]) {
case "-v": CheckBlockChain(); break;
default: AddBlock(System.Environment.GetCommandLineArgs()[0]); break;
}
}
static void AddBlock(string msg) {
var blockchain = LoadBlockChain();
if(!CheckBlockChain(blockchain)) return;
blockchain.Add(Block.New(blockchain.Count, msg, HashBlock(blockchain.Last(), msg)));
Console.WriteLine($"New Block #{blockchain.Last().Id} added to the blockchain - {blockchain.Last().Hash}");
SaveBlockChain(blockchain);
}
static bool CheckBlockChain(List<Block> blockchain = null) {
blockchain = blockchain ?? LoadBlockChain();
for(int i = 1; i<blockchain.Count; i++)
if(HashBlock(blockchain[i-1], blockchain[i]) != blockchain[i].Hash) {
Console.Error.WriteLine($"Blockchain is not valid - Block: #{i} - {blockchain[i].Hash} does not belong there.");
return false;
}
return true;
}
static string HashBlock(Block prevBlock, Block block) =>
Convert.ToBase64String(System.Security.Cryptography.SHA256.Create()
.ComputeHash(Encoding.UTF8.GetBytes($"{prevBlock.Id}{prevBlock.Value}{prevBlock.Hash}{block.Id}{block.Value}")));
static List<Block> LoadBlockChain() =>
System.IO.File.Exists("blockchain.json")
? System.Text.Json.JsonSerializer.Deserialize<List<Block>>(System.IO.File.ReadAllText("blockchain.json"))
: new List<Block> { Block.New(0, "Genesis Block") };
static void SaveBlockChain(List<Block> blockchain) =>
System.IO.File.WriteAllText("blockchain.json", System.Text.Json.JsonSerializer.Serialize(blockchain,
new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
public struct Block {
public int Id { get; set; }
public string Value { get; set; }
public string Hash { get; set; }
public static Block New(int id, string value, string hash = "") => new Block { Id = id, Value = value, Hash = hash };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment