Implementing a Simple Blockchain in C#
Published: 2023-03-15 20:12:52



Nowadays, we often hear the term "blockchain" in various contexts. While it may sound like a complex concept to grasp, it is actually straightforward and easy to implement.

So, what exactly is blockchain? Most people associate it with cryptocurrencies, but it's important to understand that blockchain is a technology that stands on its own. It is a revolutionary technology that has transformed the way we store information. Imagine a book that records every event happening in a town. Every time a new occurrence takes place, we note it down in the book. However, instead of one book, we create copies and distribute them to many people in the town, each of whom keeps their own copy of the book. Here's the interesting part: each time a new event takes place, everyone with a copy of the book verifies the accuracy of the information. If they all agree that it's true, they add the new information to their copy of the book. Since everyone has their own copy of the book, it is nearly impossible for anyone to cheat or lie since others would notice and object. This is precisely how blockchain technology works. Rather than using a physical book, we use a digital ledger to record transactions, and instead of people, we have computers worldwide that store a copy of the ledger. Whenever a new transaction occurs, all computers verify its legitimacy. If they agree, they add the new transaction to their copy of the ledger, making it difficult for anyone to cheat or deceive since others would notice and reject it.

Speaking more technically, blockchain is a distributed and decentralized digital ledger that documents transactions across multiple computers. In a blockchain, each block comprises a cryptographic hash of the preceding block, timestamp, and information about the transaction.

Let's now begin building our simple blockchain. Here are the steps you need to follow:

Set up your environment. To build a blockchain application in C#, you will need to have the .NET Core framework installed on your system. Once you have installed the framework, create a new C# console application project in Visual Studio.

Creating a block. A block in a blockchain contains transaction data, a timestamp, and a hash of the previous block. We represent a block by a hash value. Generating the hash value of a block is called “mining” the block. In C#, we can define a block as a class that has the following properties:

```
public class Block
{
  public int Index { get; set; }. 
  public DateTime Timestamp { get; set; }
  public string Data { get; set; }
  public string PreviousHash { get; set; }
  public string Hash { get; set; }
}
```

To generate a hash. We need to create a function that takes the block data and previous hash as input and outputs the hash of the block. In C#, we can use the SHA256 hashing algorithm to generate the hash of the block. Here's an example of how to generate a hash in C#:

```
public static string CalculateHash(Block block)
{
    string data = 
        $"{block.Index}{block.Timestamp}{block.Data}{block.PreviousHash}";
    
    using (SHA256 sha256 = SHA256.Create())
    {
        byte[] hashData = sha256.ComputeHash(Encoding.UTF8.GetBytes(data));
        return Convert.ToBase64String(hashData);
    }
}
```

Building the Blockchain. Now that we have a block and a way to generate the hash, we can start building the blockchain. A blockchain is a chain of blocks, where each block points to the previous block. In C#, we can create a blockchain as a list of blocks:

```
public class Blockchain { private List _chain = new List<Block>() };

public void AddBlock(Block block)
{
    if (_chain.Any())
    {
        block.PreviousHash = _chain.Last().Hash;
        block.Index = _chain.Last().Index + 1;
    }
    block.Hash = CalculateHash(block);
    _chain.Add(block);
}
```

After building the blockchain, we can validate it by adding some blocks to the blockchain and checking whether each block's hash matches the previous block's hash.

This was a short example to understand the concepts of blockchain application in your code. We created a new instance of the blockchain and add three blocks to it. We then iterated over each block in the blockchain and print out its details. We also check if the block is valid by comparing its previous hash to the hash of the previous block. In the next article, we will dig deeper into each of the concepts.