What is blockchain? Is it hard to build one? Where do you start? Which programming language should I use?
I get these questions quite often when meeting people who are interested in blockchain technology. You may also be one of those people, but don’t worry, I was, too.
4 Steps to Creating a Blockchain
- Create a block.
- Add the data (header and body) to the block.
- Hash the block.
- Chain the blocks together.
There are plenty of blockchain resources online, but it can be overwhelming and frustrating to understand as a beginner to this booming technology. However, this article is a little different than those other resources.
I’ll approach the subject in baby steps with you, and guide you through the basic concepts of blockchain and how to program one using Golang (Go).
For speed, endurance, and security, most blockchain core engines are built in C/C++ (Bitcoin, EOS, etc.…), Go (Hyperledger Fabric, Ethereum), Java (Ethereum), Rust, Haskell (Cardano) and/or Ruby (Ethereum), then provide bindings to other easy-to-use programming languages.
Also, some blockchain engines combine many programming languages for robustness and ease-of-use for developers. Ethereum is the best example of this.
What Prerequisites Do I Need to Create a Blockchain?
- A network.
- Cryptography.
- A data structure and algorithms.
- Decentralized systems.
- Javascript, Go or Python knowledge.
You only need to understand the basic concepts to program your first blockchain prototype, so let’s begin with some theories.
What Is a Blockchain?
You can’t program something you don’t understand, right? Let’s break it down. Blockchain is not Bitcoin. Blockchain is not a digital currency, Blockchain is a set of different technologies that had already existed before its creation.
So, is this a blockchain?
No, but bear with me.
Let’s simplify things with an example and some figures.
Let’s take a MySQL database that stores some information in different tables.
With the above database, there are some limitations. It allows you to do some tasks, including:
- Create, retrieve, update and delete (CRUD) operations.
- Storing the same information twice.
But its limitations are many, including:
- We can drop the entire database either mistakenly or intentionally.
- We can’t share sensitive information with others.
- It’s centralized, which means there’s a single point of failure and a security issue.
- There’s no way to trust everything that is stored in it.
- Ill-intentioned people can comprise the database.
- The database needs a manager.
- The users don’t have power over their own data
We need something different that’s transparent, reliable and independent from people. Something that’s automatic, immutable, decentralized and indestructible. That’s where blockchain kicks in.
A blockchain is a secure, trusted decentralized database and network all in one.
How Does Blockchain Work?
In other words, a blockchain is a chain of blocks. These blocks are like tables in the database, but they can’t be deleted or updated. The blocks contain information such as transactions, nonce, target bit, difficulty, timestamp, previous block hash, current block hash, Markle tree and block ID, etc, and the blocks are cryptographically verified and chained up to form an immutable chain called a blockchain or a ledger.
The same chain is then distributed to all the nodes (computers or miners) across the network via a P2P network.
So, instead of a centralized database, all the transactions (data) that are shared across the nodes are contained in blocks, which are chained together to create the ledger. This ledger represents all the data in the blockchain. All the data in the ledger is secured by cryptographic hashing and digital signature and validated by a consensus algorithm. Nodes on the network participate to ensure that all copies of the data distributed across the network are the same.
5 Key Concepts in the Blockchain Ecosystem
- Cryptographic hash and digital signature.
- Immutable ledger.
- P2P network.
- Consensus algorithm ( PoW, PoS, PBFT, ETc…).
- Block validation ( Mining, Forging, etc…).
I will explain these concepts more in detail as we go.
What Are the Benefits of Using Blockchain?
There are a number of benefits to using blockchain, including:
- Removing intermediary organizations.
- An immutable ledger
- Transparency
- Security
- Reliability
When Should You Use Blockchain?
Blockchain is not a silver bullet, so, it’s best to use it when:
- The data stored cannot be modified (proof of existence ).
- The data cannot be denied by its owner (non-repudiation).
- You want decentralization.
- You want one source of truth.
- You want high security.
- You don’t care about speed. For example, Bitcoin takes 10 minutes on average to validate a block of transactions. But some blockchains are faster because they use different consensus algorithms other than PoW. We will talk about this later.
Blockchain Use Cases
Blockchain goes beyond cryptocurrency and bitcoin. It can be used in different sectors, including:
- Real estate: Land ownership.
- Healthcare: Securely record the patient’s data.
- Finance: Reduce the taxes and intermediaries, anti-money laundering and cross border payment.
- Supply chain: Track items from the vendors to the customers, including verifying authenticity and original content creation.
- Cybersecurity: DDOS attacks.
- Giving the power back to the user: Own your data and share it securely with whom you want (DID).
- Cryptocurrency.
- Voting mechanism.
Blockchain Platforms and Applications to Know
Blockchain Types
There are three types of blockchain:
- Private: Use only internally, and when we know the users (eg. Hyperledger Fabric).
- Public: Everyone can see what is going on (Bitcoin, Ethereum).
- Hybrid: In case you want to combine the first two.
Create Your Own Blockchain
There are two ways to build a blockchain
- The easiest way is to use a pre-built blockchain open-source like Ethereum (create distributed applications, altcoins, decentralized finance (DeFi) and non-fungible tokens (NFTs), etc.), Fabric (configure a private blockchain), EOS or Cardano, etc. so that you don’t have to deal with the core engine, which is difficult to implement.
- If that doesn’t fit your requirements, then you can build one from scratch or fork, modify and/or improve an existing blockchain open-source code. For example, Litecoin and Bitcoin cash were forked from Bitcoin. This last method is tougher, more time-consuming and requires a lot of work and a strong team.
In this article, we will build a blockchain prototype from scratch so that you can thoroughly understand the blockchain’s state machine.
How to Create a Blockchain From Scratch in Go
We’re going to create the first baby blockchain in Go. You can also learn how to create it in Python, and JavaScript. These prototypes can help you understand the concepts we described earlier. We’ll complete this in four steps:
- Create a block.
- Add the data (header and body) to the block.
- Hash the block.
- Chain the blocks together.
A block contains information mentioned earlier, but to simplify things We are going to remove some. Let’s delve into the specifics.
If you aren’t familiar with Go, try to familiarize yourself with the basics, including functions, methods, data types, structures, flow controls and iterations, etc.
1. Create a Block
We’ll start with creating a folder with two files in it, main.go
and block.go
Folder structure
go // the folder
main.go // file 1
block.go // file 2
Main.go
// use the main package
package main
//import the fmt package
import (
"fmt"
)
func main(){
fmt.Println("I am building my first blockchain") // print this
CreateBlock("The hearder will be shown here", "the body will be shown here") // call the function that will create the block and pass some parameters in it.
}
If you run this program it will show an error because the CreateBlock
function is not defined yet, so go ahead and create it in block.go
.
package main
import (
"fmt" // this will help us to print on the screen
)
func CreateBlock(Header, Body string){
fmt.Println(Header ,"\n", Body) // Show me the block content
}
2. Add Data to Your Blocks.
The beauty of Go is that you don’t have to import or export functions, just declare them with capital letters, and Go will find them for you. Now, open a terminal and move to your created folder, and run go build
, then run .\go
on Windows, or ./go
on Linux and Macbook.
We just created a simple Go program that calls a function and passes some string data. Let’s add two more files, blockchain.go
and structures.go
. Now we have four files: main.go
, block.go
, structures.go
, and blockchain.go
3. Hash Your Block
I will add to each line of code some comments in order for you to understand what I am doing.
Structures.go
package main //Import the main package
// Create the Block data structure
// A block contains this info:
type Block struct {
Timestamp int64 // the time when the block was created
PreviousBlockHash []byte // the hash of the previous block
MyBlockHash []byte // the hash of the current block
AllData []byte // the data or transactions (body info)
}
// Prepare the Blockchain data structure :
type Blockchain struct {
Blocks []*Block // remember a blockchain is a series of blocks
}
Block.go
package main
import (
// We will need these libraries:
"bytes" // need to convert data into byte in order to be sent on the network, computer understands better the byte(8bits)language
"crypto/sha256" //crypto library to hash the data
"strconv" // for conversion
"time" // the time for our timestamp
)
// Now let's create a method for generating a hash of the block
// We will just concatenate all the data and hash it to obtain the block hash
func (block *Block) SetHash() {
timestamp := []byte(strconv.FormatInt(block.Timestamp, 10)) // get the time and convert it into a unique series of digits
headers := bytes.Join([][]byte{timestamp, block.PreviousBlockHash, block.AllData}, []byte{}) // concatenate all the block data
hash := sha256.Sum256(headers) // hash the whole thing
block.MyBlockHash = hash[:] // now set the hash of the block
}
// Create a function for new block generation and return that block
func NewBlock(data string, prevBlockHash []byte) *Block {
block := &Block{time.Now().Unix(), prevBlockHash, []byte{}, []byte(data)} // the block is received
block.SetHash() // the block is hashed
return block // the block is returned with all the information in it
}
/* let's now create the genesis block function that will return the first block. The genesis block is the first block on the chain */
func NewGenesisBlock() *Block {
return NewBlock("Genesis Block", []byte{}) // the genesis block is made with some data in it
}
Blockchain.go
package main
// create the method that adds a new block to a blockchain
func (blockchain *Blockchain) AddBlock(data string) {
PreviousBlock := blockchain.Blocks[len(blockchain.Blocks)-1] // the previous block is needed, so let's get it
newBlock := NewBlock(data, PreviousBlock.MyBlockHash) // create a new block containing the data and the hash of the previous block
blockchain.Blocks = append(blockchain.Blocks, newBlock) // add that block to the chain to create a chain of blocks
}
/* Create the function that returns the whole blockchain and add the genesis to it first. the genesis block is the first ever mined block, so let's create a function that will return it since it does not exist yet */
func NewBlockchain() *Blockchain { // the function is created
return &Blockchain{[]*Block{NewGenesisBlock()}} // the genesis block is added first to the chain
}
Main.go
//Time to put everything together and test
package main
import (
"fmt" // just for printing something on the screen
)
func main() {
newblockchain := NewBlockchain() // Initialize the blockchain
// create 2 blocks and add 2 transactions
newblockchain.AddBlock("first transaction") // first block containing one tx
newblockchain.AddBlock("Second transaction") // second block containing one tx
// Now print all the blocks and their contents
for _, block := range newblockchain.Blocks { // iterate on each block
fmt.Printf("Hash of the block %x\n", block.MyBlockHash) // print the hash of the block
fmt.Printf("Hash of the previous Block: %x\n", block.PreviousBlockHash) // print the hash of the previous block
fmt.Printf("All the transactions: %s\n", block.AllData) // print the transactions
} // our blockchain will be printed
}
Let’s run it now, go build then .\go
.
Voila. Easy, right?
4. Chain Your Blocks Together
Oops, our blocks in the blockchain don’t have any IDs and timestamps. So, let’s add that information by modifying the main.go
file, add these two lines in the for loop
:
fmt.Printf("Block ID : %d \n", i) fmt.Printf("Timestamp : %d \n", block.Timestamp+int64(i))
//Time to put everything together and test
package main
import (
"fmt" // just for printing something on the screen
)
func main() {
newblockchain := NewBlockchain() // Initialize the blockchain
// create 2 blocks and add 2 transactions
newblockchain.AddBlock("first transaction") // first block containing one tx
newblockchain.AddBlock("Second transaction") // second block containing one tx
// Now print all the blocks and their contents
for i, block := range newblockchain.Blocks { // iterate on each block
fmt.Printf("Block ID : %d \n", i) // print the block ID
fmt.Printf("Timestamp : %d \n", block.Timestamp+int64(i)) // print the timestamp of the block, to make them different, we just add a value i
fmt.Printf("Hash of the block : %x\n", block.MyBlockHash) // print the hash of the block
fmt.Printf("Hash of the previous Block : %x\n", block.PreviousBlockHash) // print the hash of the previous block
fmt.Printf("All the transactions : %s\n", block.AllData) // print the transactions
} // our blockchain will be printed
}
Let’s save the code and run it again, go build then ./go
.
As you can see, the blockchain is well structured. Except for the genesis block, each block contains its hash and the hash of the previous block, which makes it immutable. If the data in the block is altered, the hash will automatically change and the block will be discarded. The genesis block doesn’t have any previous hash because it’s the first one. There is no previous block.
And that’s it. Congratulations, you’ve just created your first baby blockchain in Go.
We will gradually fulfill the blockchain requirements. Blockchain is a masterpiece that needs to be engineered the way it’s supposed to be.
In blockchain, there are also two common roles. A blockchain engineer and a blockchain developer. A blockchain engineer is a professional who thoroughly understands the principles of blockchain, security, and software engineering for designing, developing, maintaining, testing and evaluating the blockchain core engines and software. A blockchain developer is a professional who builds software on top of the blockchain called decentralized applications.
Most blockchain developers use open blockchain platforms and frameworks like Ethereum, hyperledger fabric, EOS, etc. Now that you have the basics, it’s up to you to decide which one you want to be.