Overview
Have you ever became aware of Bitcoin? Have you ever before shopped Bitcoin? have you review Bitcoin? Yes, Bitcoin has actually been able to draw in the attention of the world. Bitcoin is the initial Cryptocurrency to exist today as well as stays on top of the globe listing of Cryptocurrencies. Countless individuals and also business are attempting to be as effective 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 understand what innovation lags Bitcoin and also Altcoin? That’s right, Blockchain is a technology made use of to make Cryptocurrencies.
Generally, a blockchain is simply a database application which contains deal records much like in a bank, the distinction is that the blockchain is distributed, open to the public, and also can’t be controlled or modified.
With Blockchain, you can also find out other people’s account balances, yet you don’t recognize who has them. Baffled?
What is the distinction in between an account in a financial institution as well as in a cryptocurrency? Please see some examples of account information below.
Example account information in XYZ Financial institution
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: 048e66b3e549818ea2cb354fb70749f6c8de8fa484f7530fc447d5fe80a1c424e4f5ae648d648c980ae7095d1efad87161d83886ca4b6c498ac22a93da5099014a Private Key: 09e910621c2e988e9f7f6ffcd7024f54ec1461fa6e86a4b545e9e1fe21c28866 Seed Phrase: security afford dwarf unveil during shuffle list talk rival next unknown soon
What do you require if you send out cash to Billy’s XYZ Checking account?
The response is the account number.
What do you need if you want to send out a coin to Billy’s Bitcoin account?
The solution is a Bitcoin address
What do you need if you intend to send a coin to Billy’s Ethereum account?
The answer is an Ethereum address
Thus, my little description of Cryptocurrencies and Blockchain. It will certainly help to extra conveniently understand the remainder of this write-up.
Transaction
Deals are the main factor for making Bitcoin to ensure that people can send out coins to others, get products with coins, market goods and obtain repayments with bitcoin. Blockchain should be able to store and verify purchases.
Some examples of purchases:
- 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 };
Purchase Swimming pool
In the world of blockchain, each transaction is not processed individually, but the transactions are fit in the deal swimming pool. Transaction pool is a momentary location before deals are entered into a block
For example, Bob from his mobile budget sends some coins to Billy, as well as at the same time, John sends out some coins to his close friend. Both transactions will be saved to the deal pool, after that within a specific amount of time, the purchases participated in a block.
Currently allow’s make a method AddTransactionToPool right into Blockchain course.
// 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 information blocks. A block can be presumed as a group or set of transactions, or a block can be thought about as a web page in a ledger.
Block knows such as ID, height, hash, previous hash, timestamp, deals, maker.
Allow’s start by creating a design for Block.
public class Block { public int Height { get; set; } public Int64 TimeStamp { get; set; } public byte[] PrevHash { get; set; } public byte[] Hash { get; set; } public Transaction[] Transactions { get; set; } public string Creator { get; set; } }
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 also Hash are block headers while Purchases are the body of the block.
Let’s make code as an instance of creating a brand-new block.
//Create one transaction var trx1 = new Transaction { Sender = "Johana", Recipient = "Merlin", Amount = 3.0, Fee = 0.3 }; //insert transaction into list Transaction[] lsTrx = {trx1}; //asume previous hash is empty var prevHash = System.Text.Encoding.UTF8.GetBytes(""); //create new Block var block = new Block(0, String.Empty.ConvertToBytes(), lsTrx, "Admin");
Making a hash
A hash is a feature that transforms an input of letters and numbers right into an encrypted output of a taken care of length. A hash is developed using a formula. Hash is extremely vital as well as this attribute makes blockchain safe.
When computing a hash we need some data from a block such as a TimeStamp, Transactions, and also Previous Hash.
Allow’s make an approach GenerateHash() inside the Block course.
using System; using System.Collections.Generic; using System.Security.Cryptography; using Utils; namespace Models { public class Block { public int Height { get; set; } public long TimeStamp { get; set; } public byte[] PrevHash { get; set; } public byte[] Hash { get; set; } public Transaction[] Transactions { get; set; } public string Creator { get; set; } public Block(int height, byte[] prevHash, List<Transaction> transactions, string creator) { Height = height; PrevHash = prevHash; TimeStamp = DateTime.Now.Ticks; Transactions = transactions.ToArray(); Hash = GenerateHash(); Creator = creator; } // generate hash of current block public byte[] GenerateHash() { var sha = SHA256.Create(); byte[] timeStamp = BitConverter.GetBytes(TimeStamp); var transactionHash = Transactions.ConvertToByte(); byte[] headerBytes = new byte[timeStamp.Length + PrevHash.Length + transactionHash.Length]; Buffer.BlockCopy(timeStamp, 0, headerBytes, 0, timeStamp.Length); Buffer.BlockCopy(PrevHash, 0, headerBytes, timeStamp.Length, PrevHash.Length); Buffer.BlockCopy(transactionHash, 0, headerBytes, timeStamp.Length + PrevHash.Length, transactionHash.Length); byte[] hash = sha.ComputeHash(headerBytes); return hash; } } }
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, the same and available to the public. Blockchain shops deals by grouping them right into teams called block.
The number of transactions that can be entered into a block might not go beyond the specified restriction, as an example, the limit is 200.
Having a block in the blockchain occurs every certain period of time, for example, every one minute.
Let’s code for blockchain
In actual blockchain applications, they use a data source to hold all blocks. Right here I will use List just for instance.
public class Blockchain { public IList<Block> Blocks { set; get; } }
Add Block for blockchain
Let’s make a function to add a block to Blockchain.
// Add new Block to blockchain public void AddBlock(Transaction[] transactions) { var lastBlock = GetLastBlock(); var nextHeight = lastBlock.Height + 1; var prevHash = lastBlock.Hash; var timestamp = DateTime.Now.Ticks; var block = new Block(nextHeight, prevHash, transactions, "Admin"); Blocks.Add(block); }
Genesis Block
The genesis block is a block that is in the first position on the blockchain. This block has no previous block.
private Block CreateGenesisBlock() { var lst = new List<Transaction>(); var trx = new Transaction { Amount = 1000, Sender = "System", Recipient = "Genesis Account", Fee = 0.0001 }; lst.Add(trx); var trxByte = lst.ToArray().ConvertToByte(); return new Block(1, String.Empty.ConvertToBytes(), lst.ToArray(), "Admin"); }
Getting Information From Blockchain
When blockchain has data, we can gather some details 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 genuine blockchain, they have block travelers. Within block traveler, we can see all blocks in the blockchain, block header, deal history, deal details, and so forth.
We require a method to print all the blocks in the blockchain.
/** * Print all block in blockchain */ public void PrintBlocks() { Console.WriteLine("\n\n====== Blockchain Explorer ====="); foreach (Block block in Blocks) { PrintBlock(block); } } private void PrintBlock(Block block) { Console.WriteLine("Height :{0}", block.Height); Console.WriteLine("Timestamp :{0}", block.TimeStamp.ConvertToDateTime()); Console.WriteLine("Prev. Hash :{0}", block.PrevHash.ConvertToHexString()); Console.WriteLine("Hash :{0}", block.Hash.ConvertToHexString()); Console.WriteLine("Transactins :{0}", block.Transactions.ConvertToString()); Console.WriteLine("Creator :{0}", block.Creator); Console.WriteLine("--------------"); }