Creating Simple Cryptocurrency using .NET and C# — Part 1. Basic

Putu Kusuma
6 min readFeb 3, 2020
Image by WorldSpectrum from Pixabay

Overview

Have you ever heard about Bitcoin? Have you ever tried to buy Bitcoin? have you read about Bitcoin? Yes, Bitcoin has been able to attract the attention of the world. Bitcoin is the first Cryptocurrency to exist today and remains at the top of the world list of Cryptocurrencies. Thousands of people and companies are trying to be as successful as Bitcoin. They make new coins. These coins are called Altcoin.

Now there are more than three thousand Altcoins such as Ethereum, Tether, XRP, Litecoin, Bitcoin Cash, Cardano, Binance Coin, Polkadot, Stellar, USD coin, Monero.

Do you know what technology is behind Bitcoin and Altcoin? That’s right, Blockchain is a technology used to make Cryptocurrencies.

Basically, a blockchain is just a database application that contains transaction records just like in a bank, the difference is that the blockchain is distributed, open to the public, and can’t be manipulated or altered.

With Blockchain, you can even find out other people’s account balances, but you don’t know who owns them. Confused?

What is the difference between an account in a bank and in a cryptocurrency? Please see some examples of account details below.

Example account details in XYZ Bank

Name: Putu Kusuma
Account Number: 0987–0989–0909
Address: Denpasar City, Bali, Indonesia
----------
Birth Date: 10 August 1990
Birth Place: Denpasar, Bali
Phone: +62–87686XXX
ID Card Number: 89800890909XXX
Tax Number: 8989–9090–9080
Mother Name: bla bla
Marriage status: single

Example account details for Bitcoin

Address: 
bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
Publik Key:
1DSsgJdB2AnWaFNgSbv4MZC2m71116JafG
Private Key:
E9873D79C6D87DC0FB6A5778633389_SAMPLE_PRIVATE_KEY_DO_NOT_IMPORT_F4453213303DA61F20BD67FC233AA33262
Seed Phrase:
excuse plastic lady travel junk slush tornado exit usage scare deposit immense

Example Account information in Ethereum

Address: 
0x00B54E93EE2EBA3086A55F4249873E291D1AB06C
Public Key: 048e66b3e549818ea2cb354fb70749f6c8de8fa484f7530fc447d5fe80a1c424e4f5ae648d648c980ae7095d1efad87161d83886ca4b6c498ac22a93da5099014aPrivate Key:
09e910621c2e988e9f7f6ffcd7024f54ec1461fa6e86a4b545e9e1fe21c28866
Seed Phrase:
security afford dwarf unveil during shuffle list talk rival next unknown soon

What do you need if you send money to Billy's XYZ Bank account?
The answer is the account number.

What do you need if you want to send a coin to Billy’s Bitcoin account?
The answer is a Bitcoin address

What do you need if you want to send a coin to Billy’s Ethereum account?
The answer is an Ethereum address

Thus, my little explanation of Cryptocurrencies and Blockchain. It will help to more easily understand the rest of this article.

Requirements

.NET SDK 5.0
Visual Studio Community Edition

Transaction

Transactions are the main reason for making Bitcoin so that people can send coins to others, buy goods with coins, sell goods and receive payments with bitcoin. Blockchain should be able to store and validate transactions.

Some examples of transactions:

- Bob sends a coin to Billy, amount: $10, fees: $0.01
- John buy shoes from Ivanka, amount: $20, fees: $0.01
- Antonio sells a watch to Robert, amount: $30, fees: $0.01

Let’s make code for this Transaction class.

public class Transaction
{
public long TimeStamp { get; set; }
public string Sender { set; get; }
public string Recipient { set; get; }
public double Amount { set; get; }
public double Fee { set; get; }
}

Now let’s make code to define a new transaction.

// Create new transaction
var trx1 = new Transaction
{
TimeStamp = DateTime.Now.Ticks,
Sender = "Bob",
Recipient = "Billy",
Amount = 10,
Fee = 0.01
};
// Create new transaction
var trx1 = new Transaction
{
TimeStamp = DateTime.Now.Ticks,
Sender = "John",
Recipient = "Ivanka",
Amount = 20,
Fee = 0.01
};
// Create new transaction
var trx1 = new Transaction
{
TimeStamp = DateTime.Now.Ticks,
Sender = "Robert",
Recipient = "Antonio",
Amount = 30,
Fee = 0.01
};

Transaction Pool

In the world of blockchain, each transaction is not processed one by one, but the transactions are accommodated in the transaction pool. Transaction pool is a temporary place before transactions are entered into a block

For example, Bob from his mobile wallet sends some coins to Billy, and at the same time, John sends some coins to his friend. Both transactions will be saved to the transaction pool, then within a certain period of time, the transactions entered into a block.

Now let’s make a method AddTransactionToPool into Blockchain class.

// transaction pool
public List<Transaction> TransactionPool = new List<Transaction>();

// Add a transaction to pool
public void AddTransactionToPool(Transaction trx)
{
TransactionPool.Add(trx);
}

Block

Blockchain is a chain of data blocks. A block can be assumed as a group or batch of transactions, or a block can be considered as a page in a ledger.

Block has information such as ID, height, hash, previous hash, timestamp, transactions, creator.

Let’s start by creating a model for Block.

Height — is a sequence number of blocks.
TimeStamp — is the time when the block was created.
Hash — is the hash of the block. The hash can be imagined as the unique identity of the block. There are no blocks that have the same hash.
PrevHash — is a hash of the previous block.
Transactions — are collections of transactions that occur, as previously discussed above.
Creator — is who creates the block identified by the public key.

In the blockchain PreviousHash, TimeStamp and Hash are block headers while Transactions are the body of the block.

Let’s make code as an example of creating a new block.

Making a hash

A hash is a function that converts an input of letters and numbers into an encrypted output of a fixed length. A hash is created using an algorithm. Hash is very important and this feature makes blockchain safe.

When calculating a hash we need some data from a block such as a TimeStamp, Transactions, and Previous Hash.

Let’s make a method GenerateHash() inside the Block class.

Here is the explanation:

// 1. convert timestamp to byte
byte[] timeStamp = BitConverter.GetBytes(TimeStamp);
// 2. convert transactions to byte
byte[] transactionHash = Transactions.ConvertToByte();
// 3. get PrevHash // 3. create new array bytes
byte[] headerBytes = new byte[timeStamp.Length + PrevHash.Length + transactionHash.Length];
// 4. copy bytes of timestamp, transactions and previous hash to header byte// 5. Calculate hash of headerBytes
byte[] hash = sha.ComputeHash(headerBytes);

Blockchain

Blockchain is a transaction record that is shared and stored on a distributed computer, unchanged and open to the public. Blockchain stores transactions by grouping them into groups called block.

The number of transactions that can be entered into a block may not exceed the specified limit, for example, the limit is 200.

Having a block in the blockchain occurs every certain period of time, for example, every 60 seconds.

Let's code for blockchain

In real blockchain applications, they use a database to hold all blocks. Here I will use List just for example.

Add Block for blockchain
Let’s make a function to add a block to Blockchain.

Genesis Block

The genesis block is a block that is in the first position on the blockchain. This block has no previous block.

Getting Data From Blockchain

When blockchain has data, we can collect some information from the blockchain.

Genesis Block
The genesis block is the first block on the blockchain

public void PrintGenesisBlock()
{
Console.WriteLine("\n\n==== Genesis Block ====");
var block = Blocks[0];
PrintBlock(block);
}

Last Block
The Genesis block is the last block on the blockchain

public void PrintLastBlock()
{
Console.WriteLine("\n\n==== Last Block ====");
var lastBlock = GetLastBlock();
PrintBlock(lastBlock);
}

Balance

To find a balance for an account, check existing transactions and filter by name, and then calculate the balance.

/**
* Print balance by name
**/
public void PrintBalance(string name)
{
Console.WriteLine("\n\n==== Balance for {0} ====", name);
double balance = 0;
double spending = 0;
double income = 0;
foreach (Block block in Blocks)
{
var transactions = block.Transactions;
foreach (var transaction in transactions)
{
var sender = transaction.Sender;
var recipient = transaction.Recipient;
if (name.ToLower().Equals(sender.ToLower()))
{
spending += transaction.Amount + transaction.Fee;
}
if (name.ToLower().Equals(recipient.ToLower()))
{
income += transaction.Amount;
}
balance = income - spending;
}
}
Console.WriteLine("Balance :{0}", balance);
Console.WriteLine("---------");
}

Transaction History
To get the transaction history for an account, check the transaction and filter by name.

/**
* Get transactions by name
**/
public void PrintTransactionHistory(string name){ Console.WriteLine("\n\n==== Transaction
History for {0} ===", name);
foreach (Block block in Blocks){
var transactions = block.Transactions;
foreach (var transaction in transactions){
var sender = transaction.Sender;
var recipient = transaction.Recipient;
if (name.ToLower().Equals(sender.ToLower())
|| name.ToLower().Equals(recipient.ToLower()))
{
Console.WriteLine("Timestamp :{0}", transaction.TimeStamp);
Console.WriteLine("Sender :{0}", transaction.Sender);
Console.WriteLine("Recipient :{0}", transaction.Recipient);
Console.WriteLine("Amount :{0}", transaction.Amount);
Console.WriteLine("Fee :{0}", transaction.Fee);
Console.WriteLine("--------------");
}
}
}
}

Block Explorer

In the real blockchain, they have block explorers. Within block explorer, we can see all blocks in the blockchain, block header, transaction history, transaction details, and so on.
We need a method to print all the blocks in the blockchain.

Source code:
https://github.com/jhonkus/UbudKusCoin/tree/part_1_basic

Post List:

Thank you for reading my post. If this post is helpful please give me a bunch of claps.

--

--