Simplest Blockchain in C#
Tags: blockchain, dotnet, csharp
Published: 2020-01-10 16:40:56

I'm pretty sure that almost every developer in the world has heard of **Blockchain**, some wrongly consider it as [Bitcoin](https://bitcoin.org/en/) and some may not know how it exactly works. So this post aims to explain what exactly Blockchain is and how to create a simple blockchain in ".Net Core" using C#, and to figure out how Blockchain really works at the end.
{% github  amir-ashy/Blockchain no-readme %}
####What will be covered####
+ Defining models ([Transaction](https://github.com/amir-ashy/Blockchain/blob/master/Model/Transaction.cs) + [Block](https://github.com/amir-ashy/Blockchain/blob/master/Model/Block.cs))
+ Using [TransactionPool](https://github.com/amir-ashy/Blockchain/blob/master/TransactionPool.cs) for storing raw Transactions
+ Using hash algorithm in order to create immutability
+ Creating a block mining unit which mine blocks after a period of time
+ Using [embedio](https://github.com/unosquare/embedio) in order to view our blockchain in a web browser

###What is Blockchain###
Literally, Blockchain is a chain of blocks which could be simply assumed as an immutable data structure. Immutability is one of the most prominent features of a blockchain, which leads us to build trust in completely unreliable environments.
This kind of immutability is achieved by using Cryptographic hashing algorithms, (in our case we use **Double SHA256**). which prevents data from being changed or deleted after data is added to the Blockchain.
As it's obvious in the following image; Two different hashes are stored in every block, one hash is calculated for the current block and the other, is for the previous one. so any change in a block invalidates every block after it.
![Blocks in Blockchain](https://thepracticaldev.s3.amazonaws.com/i/fd8k90k557nb516mnm1u.png)
###Let's Start Coding!###
First of all, as we are to use ".Net Core", it's necessary to install ".NET Core" 3.1 Framework (or any other preferred version).
You could find more about installation [here](https://dotnet.microsoft.com/download/dotnet-core/3.1).
After installation completes, we should create our project using dotnet CLI
```
dotnet new console Blockchain.
```
As we are going to use [embedio](https://github.com/unosquare/embedio) and [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json), we add their corresponding packages to our project, again with dotnet CLI
```
dotnet add package Newtonsoft.Json
dotnet add package EmbedIO

```
Now that our project is ready, let's define our data models. Our first step is to define a model for transaction.
{% gist https://gist.github.com/amir-ashy/b56bf5d082d442e508024186e2191cf4 %}
The *From* property identifies the sender of the money, the *To* property identifies the receiver of the money and the *Amount* represents the amount of money sent. 
Let's create our next model, which is a Block's model. As we know, Each block contains data that will be written to the blockchain. Block data model has a list of transactions which are processed in the current block and two strings for storing hashes of the current Block(*Hash*) and the previous one(*PrevHash*). There are two other properties in every Block, Nounce is used for the mining algorithm and TimeStamp goes for DateTime of Creation of Block.
{% gist https://gist.github.com/amir-ashy/2cc76e2bfa6ac4ba3680f0088f917ab1 %}
It's time to define our Transaction Pool class, which is used for storing unprocessed transactions during the time that a transaction is received and added to our blockchain. there are two methods in Transaction pool; one for adding raw Transactions (*AddRaw*), and the other one for getting all unprocessed transactions(*TakeAll*).
{% gist https://gist.github.com/amir-ashy/927acaa650da2b21a8fce3f05f98cdb7 %}
This is the time to define our main class which is [BlockMiner](https://github.com/amir-ashy/Blockchain/blob/master/BlockMiner.cs) class. First, we model out the blockchain itself which is simply a list of Blocks.
{% gist https://gist.github.com/amir-ashy/1780206f056b865d5e53a8f41b8658ea %}
We should now define a function which is responsible for calculating hash of raw string data and returning the result as hashed string. As it's obvious we are using SHA256 algorithm since it has been used in other famous blockchains like Bitcoin.
{% gist https://gist.github.com/amir-ashy/af3000ae279c17a2729c609019eeeff9 %}
So as we create our hashing function, now we have to find a way to calculate hash of our block. The primary problem we're facing here is to find a way to calculate a hash for the list of transactions existing in the ongoing block. As you may know already **Merkle Tree** is what comes into use here. You can learn more about it [here](https://brilliant.org/wiki/merkle-tree/)
![Merkle Tree](https://upload.wikimedia.org/wikipedia/commons/9/95/Hash_Tree.svg)
Notice that by using Merkle tree any little change in a transaction will lead to change in Block's hash and will effect every other Block after corresponding block.
We simply use discussed algorithm to calculate hash of all transactions in a block.
{% gist https://gist.github.com/amir-ashy/1e38294b48ef76a667008ce1ba216f90 %}
Now we need to write our mining function that tries to find appropriate **Hash** for our ongoing block (starts with specific amount of '0' at the start of hash). The way that we extract the appropriate hash is by incrementing nounce property defined in block and calculating the hash again and again until we reach our goal. Originally this kind of mining algorithms are called *Proof of work* which are very useful these days.
{% gist https://gist.github.com/amir-ashy/7b07c09e70514b175d86f13358c19284 %}
After our mining process is done we can simply add our mined block to the blockchain. 
At this point, we need one extra function in BlockMiner class which is responsible for continuously mining Blocks and we need two final functions to *start* and *stop* the mining process.
{% gist https://gist.github.com/amir-ashy/ae23c9484d6652e7721e795ea2ad31b9 %}
Let's create our HTTP server using [embedio](https://github.com/unosquare/embedio) which is a tiny, cross-platform, module based web server.
{% gist https://gist.github.com/amir-ashy/a385b48d06918f3e916f6579296e4d3f %}
Our controller has four methods, three of them will be used for exposing blockchain data and the other one will be used for adding new transactions to blockchain.
#### We’re done!####
Let’s try it out now. 
Fire up your application from terminal using command below
```
dotnet run
```
you will see something like this in your terminal
![app run](https://thepracticaldev.s3.amazonaws.com/i/enh9h9a8zlgijr30vwqy.JPG)
Now, let’s send some POST requests to add blocks.
![Post](https://thepracticaldev.s3.amazonaws.com/i/dlnvmlo8kp7410majmcz.JPG)
Now if you navigate to http://localhost:5449/api/blocks/latest or http://localhost:5449/api/blocks you will see mined blocks directly in your browser.
![mined block](https://thepracticaldev.s3.amazonaws.com/i/pgjg7o3itv4xeien9cbt.JPG)