Building A Blockchain In .NET Core - Basic Blockchain

Introduction

Blockchain technology is the foundation of Bitcoin, the most popular cryptocurrency in the world. With the popularity of Bitcoin, Blockchain has also got great exposure. People have now started to use Blockchain in other-than-cryptocurrency kinds of applications too. Looking at Satoshi Nakamoto's (the founder of blockchain) Bitcoin whitepaper, you could get confused about how bitcoin works. Today, I am going to build a blockchain from scratch to help everybody understand the mechanism of the blockchain.

What is Blockchain?

Blockchain is a database. What is a database? A database is an organized collection of data. Or, you can say, a data structure that stores the data. Therefore, Blockchain is just a data structure that stores the data. As the name hinted, there will be a chain of blocks. 

Chain of Blocks

Below is the architecture diagram of a basic blockchain.

Blockchain

This basic blockchain has a linked list that is composed of blocks. Each block has the following properties.

  • Index
  • Timestamp
  • Previous Hash
  • Hash
  • Data

The first block is a special block: genesis block. The genesis block is the only block that has no previous blocks and does not contain data.

Implementation

We will add two classes for this data structure: Block and Blockchain.

Block

public class Block   
{   
    public int Index { get; set; }   
    public DateTime TimeStamp { get; set; }   
    public string PreviousHash { get; set; }   
    public string Hash { get; set; }   
    public string Data { get; set; }   
    public Block(DateTime timeStamp, string previousHash, string data)   
    {   
        Index = 0;   
        TimeStamp = timeStamp;   
        PreviousHash = previousHash;   
        Data = data;   
        Hash = CalculateHash();   
    }   
    public string CalculateHash()   
    {   
        SHA256 sha256 = SHA256.Create();   
        byte[] inputBytes = Encoding.ASCII.GetBytes($"{TimeStamp}-{PreviousHash ?? ""}-{Data}");   
        byte[] outputBytes = sha256.ComputeHash(inputBytes);   
        return Convert.ToBase64String(outputBytes);   
    }   
}  

Blockchain

public class Blockchain   
{   
    public IList<Block> Chain { set;  get; }   
    public Blockchain()   
    {   
        InitializeChain();   
        AddGenesisBlock();   
    }   
    public void InitializeChain()   
    {   
        Chain = new List<Block>();   
    }   
    public Block CreateGenesisBlock()   
    {   
        return new Block(DateTime.Now, null, "{}");   
    }   
    public void AddGenesisBlock()   
    {   
        Chain.Add(CreateGenesisBlock());   
    }   
    public Block GetLatestBlock()   
    {   
        return Chain[Chain.Count - 1];   
    }   
    public void AddBlock(Block block)   
    {   
        Block latestBlock = GetLatestBlock();   
        block.Index = latestBlock.Index + 1;   
        block.PreviousHash = latestBlock.Hash;   
        block.Hash = block.CalculateHash();   
        Chain.Add(block);   
    }   
}  

After we have those two classes, we can create an instance of the new blockchain.

Program

And, we can add blocks to it.

Add new block

Given below is the code.

Blockchain phillyCoin = new Blockchain();   
phillyCoin.AddBlock(new Block(DateTime.Now, null, "{sender:Henry,receiver:MaHesh,amount:10}"));   
phillyCoin.AddBlock(new Block(DateTime.Now, null, "{sender:MaHesh,receiver:Henry,amount:5}"));   
phillyCoin.AddBlock(new Block(DateTime.Now, null, "{sender:Mahesh,receiver:Henry,amount:5}"));   
Console.WriteLine(JsonConvert.SerializeObject(phillyCoin, Formatting.Indented));   

The Blockchain information will be serialized into JSON and the output in the console.

Validation

One of the advantages of using blockchain is data security. Data security means that tampering with the old data and altering the method of securing new data is prevented by both the cryptographic method and the non-centralized storage of the data itself. However, blockchain is just a data structure in which data can be easily changed like this.

phillyCoin.Chain[1].Data = "{sender:Henry,receiver:MaHesh,amount:1000}";

 Therefore, we need a way to validate the data. This is why I have added an IsValid method to the code.

public bool IsValid()
{
    for (int i = 1; i < Chain.Count; i++)
    {
        Block currentBlock = Chain[i];
        Block previousBlock = Chain[i - 1];
        if (currentBlock.Hash != currentBlock.CalculateHash())
        {
            return false;
        }
        if (currentBlock.PreviousHash != previousBlock.Hash)
        {
            return false;
        }
    }
    return true;
}

The IsValid method will check two things.

  • Each block’s hash to see if the block is changed
  • Previous block’s hash to see if the block is changed and recalculated

Then, we call the IsValid before the data tampering and after the data tampering to see if there are any data issues.

Console.WriteLine($"Is Chain Valid: {phillyCoin.IsValid()}");
Console.WriteLine($"Update amount to 1000");
phillyCoin.Chain[1].Data = "{sender:Henry,receiver:MaHesh,amount:1000}";
Console.WriteLine($"Is Chain Valid: {phillyCoin.IsValid()}");

How about the case when the attacker recalculates the hash of the tampered block?

phillyCoin.Chain[1].Hash = phillyCoin.Chain[1].CalculateHash();  

The Validation result will still be false because the validation not only looks at the current block but also at the link to the previous block.

Now, what about the case when an attacker recalculates hashes of all the current blocks and the following blocks?

Console.WriteLine($"Update the entire chain");
phillyCoin.Chain[2].PreviousHash = phillyCoin.Chain[1].Hash;
phillyCoin.Chain[2].Hash = phillyCoin.Chain[2].CalculateHash();
phillyCoin.Chain[3].PreviousHash = phillyCoin.Chain[2].Hash;
phillyCoin.Chain[3].Hash = phillyCoin.Chain[3].CalculateHash();

After all the Blocks are recalculated, the verification is passed. However, this is only passed on to one node because Blockchain is a decentralized system. Tampering with one node could be easy but tampering with all the nodes in the system is impossible.

Summary

A Blockchain is a chain of blocks. It uses cryptography to ensure data integrity.  You can open and run the sample code in Visual Studio 2017. This is the first article in my "Building a Blockchain in .NET Core" series.

Next article: Building Proof Of Work in a Blockchain using .NET Core


Similar Articles