Building A Blockchain In .NET Core - Transaction And Reward


In my previous article, I talked about Proof of Work. Proof of Work requires a lot of computing time, in turn, it uses a lot of electricity. One example is that the power consumed by the entire Bitcoin network in November 2017 is higher than that of Ireland. All the nodes in Bitcoin network are volunteers that they “donate” their computing time to the network. The question is why people want to connect their computer to a Blockchain network and use their computing time to help on Proof of Work? The answer is an award.

Please check previous articles,

Hash, Mining, and Award

The most popular Blockchain network at this moment is Bitcoin. It is a digital currency that has no central authority. Proof of Work allows Bitcoin to maintain security and validity without a middleman, bank. However, the price is a lot of computing time, therefore a lot of electricity. The computing time used in Proof of Work is to fulfill cryptographic requirements. The cryptographic requirements are in place for data validation. More specifically, a hash of a block is generated for validating the block by any nodes. The SHA256 hash algorithm guarantees that the generated hash code is completely random. It is chosen by Blockchain as the hash algorithm. To generate a hash is trivial, but to generate a specific hash is difficult and time-consuming. The goal is to find a hash that matches with a dictated difficulty. The only way to find the right hash is the brutal force approach, means try it again and again. The finding hash process is done by the entire network. Every node in the network competes with other nodes to find the right hash and to get the award. The award is a new transaction that gives a certain amount of digital currency to the node who found a right hash and added a new block. This process is called mining and computers which help on find a new hash code and add a new block are called miner. The awarded currency is new currency in the circulation. So, ming process is also a currency creating process in Blockchain.


Before we update our Blockchain to provide award feature, we want to refactor our code to have a clearly defined transaction in place


A new Class, Transaction, is created to contain information that was contained in JSON format.


  1. public class Transaction  
  2. {  
  3.     public string FromAddress { get; set; }  
  4.     public string ToAddress { get; set; }  
  5.     public int Amount { get; set; }  
  7.     public Transaction(string fromAddress, string toAddress, int amount)  
  8.     {  
  9.         FromAddress = fromAddress;  
  10.         ToAddress = toAddress;  
  11.         Amount = amount;  
  12.     }  
  13. }  

After added Transaction class, we can update our Block to replace Data with Transactions. One misunderstanding I had before was that one Blockchain can only contain one transaction. Actually, one block can contain many transactions. Therefore, we uses a collection to store transaction data. 

  1. public IList<Transaction> Transactions { get; set; } 

The CalculateHash method is also updated to use Transactions instead of Data to get hash of a block.

  1. public string CalculateHash()  
  2. {  
  3.     SHA256 sha256 = SHA256.Create();  
  5.     byte[] inputBytes = Encoding.ASCII.GetBytes($"{TimeStamp}-{PreviousHash ?? ""}-{JsonConvert.SerializeObject(Transactions)}-{Nonce}");  
  6.     byte[] outputBytes = sha256.ComputeHash(inputBytes);  
  8.     return Convert.ToBase64String(outputBytes);  
  9. }  


The new block generating process is a time-consuming process. But, a transaction can be submitted anytime, so we need to have a place to store transactions before they are processed. Therefore, we added a new field, PendingTransactions, to store newly added transactions.

  1. IList<Transaction> PendingTransactions = new List<Transaction>();  

We added a CreateTransaction method to add a new transaction to the PendingTransaction collection.

  1. public void CreateTransaction(Transaction transaction)  
  2. {  
  3.     PendingTransactions.Add(transaction);  

Accordingly, Program is changed to pass a transactions into a blockchain

  1. Blockchain phillyCoin = new Blockchain();  
  2. phillyCoin.CreateTransaction(new Transaction("Henry""MaHesh", 10));  

The following diagram shows how everything works together



The incentive for miners to continue providing their computing time to generate new blocks is awarded. Awards are given after processed transactions and adding a new block.


We need to update Blockchain and add a ProcessPendingTransactions method. This method needs a miner address as the parameter.

  1. public void ProcessPendingTransactions(string minerAddress)  
  2. {  
  3.     Block block = new Block(DateTime.Now, GetLatestBlock().Hash, PendingTransactions);  
  4.     AddBlock(block);  
  6.     PendingTransactions = new List<Transaction>();  
  7.     CreateTransaction(new Transaction(null, minerAddress, Reward));  
  8. }  

In the ProcessPendingTransaction method, after all, pending transactions are processed, the PendingTransactions field is reset and then a new transaction is added to give the reward to the miner. The reward is predefined in our basic Blockchain as one cryptocurrency.



We changed the program accordingly to process transactions.

  1. Blockchain phillyCoin = new Blockchain();  
  2. phillyCoin.CreateTransaction(new Transaction("Henry""MaHesh", 10));  
  3. phillyCoin.ProcessPendingTransactions("Bill");  
  4. Console.WriteLine(JsonConvert.SerializeObject(phillyCoin, Formatting.Indented));  

Run the and program we can see the state of the Blockchain.


From the screenshot, you can see there are two blocks. The first block is the genesis block and the second block is a normal block that contains a transaction from Henry to Mahesh. But, where is the reward transaction? The reward transaction is not there because the reward was added after a new block is processed. It will show up in the next block.

We can add more transactions into the Blockchain and process them again,

  1. static void Main(string[] args)  
  2. {  
  3.     var startTime = DateTime.Now;  
  5.     Blockchain phillyCoin = new Blockchain();  
  6.     phillyCoin.CreateTransaction(new Transaction("Henry""MaHesh", 10));  
  7.     phillyCoin.ProcessPendingTransactions("Bill");  
  8.     Console.WriteLine(JsonConvert.SerializeObject(phillyCoin, Formatting.Indented));  
  10.     phillyCoin.CreateTransaction(new Transaction("MaHesh""Henry", 5));  
  11.     phillyCoin.CreateTransaction(new Transaction("MaHesh""Henry", 5));  
  12.     phillyCoin.ProcessPendingTransactions("Bill");  
  14.     var endTime = DateTime.Now;  
  16.     Console.WriteLine($"Duration: {endTime - startTime}");  
  18.     Console.WriteLine("=========================");  
  19.     Console.WriteLine($"Henry' balance: {phillyCoin.GetBalance("Henry")}");  
  20.     Console.WriteLine($"MaHesh' balance: {phillyCoin.GetBalance("MaHesh")}");  
  21.     Console.WriteLine($"Bill' balance: {phillyCoin.GetBalance("Bill")}");  
  23.     Console.WriteLine("=========================");  
  24.     Console.WriteLine($"phillyCoin");  
  25.     Console.WriteLine(JsonConvert.SerializeObject(phillyCoin, Formatting.Indented));  
  27.      Console.ReadKey();  
  28. }  

After running the program, balance and state of the blockchain are displayed on the screen like the below:


You can see the reward transaction is in the 3rd block because it was added after the second block. In the meantime, you may notice the balance of the blockchain is 1 cryptocurrency right now instead of 0. So, the mining process “printed” new cryptocurrency and added it into the circulation.


I did further refactor and add transaction and reward into the basic blockchain. We have a more completed Blockchain right now. However, everything we have so far works only on one computer. The blockchain is a decentralized, distributed network. How to build a network and let computers join the network as a node and talk to each other. It will be the next thing I want to cover in my next article.