Is It Hard to Build a Blockchain From Scratch?

Sinai Nday
Jan 14 · 8 min read

Episode 1
In Golang

What is blockchain? is it hard to build one? where to start from? which programming language to use?

Trust me I got these questions quite often when meeting people who are interested in blockchain technology. You may also be part of them, don’t worry I was too.

At some point, it became tiring for me to answer the same questions repeatedly to every single person. Thus, I decided to start a series of articles so I can just share the link. Easy right?😊.

Photo by Daniel von Appen on Unsplash

There are plenty of blockchain resources online, but it’s overwhelming and frustrated to understand them as a newbie to this booming technology. however, this article is a little different.

In this article, I will take a baby step with you, and you will understand the basic concepts of blockchain and how to program one using Python, Javascript, or Go (Golang).

I chose these languages because most people are familiar with them, especially javascript and python. But for speed, endurance and security most blockchain core engines are built-in c/c++ (Bitcoin, EOS), Go (Hyperledger Fabric, Ethereum), Java (Ethereum), Rust, Haskell (Cardano) and/or Ruby (Ethereum) then provide bindings to other easy-to-use programming languages.

In addition, some blockchain engines combine many programming languages for robustness and easy to use for developers, Ethereum is the best use case.

Prerequisites:

  • Network
  • Cryptography
  • Data structure and algorithms
  • Distributed systems
  • Javascript/ Go / Python

You only need basic concepts to program your fist blockchain prototype.

  1. What is Blockchain?

You can’t program something you don’t understand, right?. Let’s break things down, blockchain is not bitcoin, blockchain is not a digital currency, blockchain is a set of different technologies that already existed before.

So is this a blockchain man?

No, bear with me😁.

Let’s simplify things by giving an example because engineers understand better with figures.

Let’s take a MySQL database that stores some information.

By Nday Sinai

With the above database, we can :

  1. Do some CRUD (Create, Retrieve, Update and Delete) operations,
  2. Store the same information twice,
  3. Drop the entire database,
  4. We cannot share sensitive information with others,
  5. The DB can be centralized ( Single point of failure, security issue),
  6. There is no way to trust everything that is stored in it.
  7. Some databases can allow relationships among tables (eg. RDBMS) and others cannot tolerate that (eg. NoSQL databases),
  8. The database can be blown up by ill-intentioned people
  9. Need a DB manager ( He/She can alter or compromise the information)
  10. The users don’t have power over their own data
  11. Etc…

So why if we need something different, something reliable, something independent from people, something automatic, something immutable? that’s where blockchain kicks in.

A blockchain is a secure, trusted decentralized database and network all in one😎.

“Truth can only be found in one place: the code. ”

A blockchain is a chain of blocks, blocks are like tables in the database but they cannot be deleted or updated, blocks contain information called transactions and other additional data. the blocks are cryptographically verified and chained up to form an immutable chain of blocks called a blockchain or ledger.

By Nday Sinai

The same chain is then distributed to all the nodes across the network via a P2P network.

By Nday Sinai

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 to remember in the blockchain ecosystem:

  1. Cryptographic hash and digital signature
  2. Immutable ledger
  3. P2P network
  4. Consensus algorithm ( PoW, PoS, PBFT, ETc…)
  5. Block validation ( Mining, Forging, etc…)

I will explain these concepts more in detail as we go.

Benefits of using blockchain:

  1. Remove intermediary organizations
  2. Immutable ledger
  3. Transparency
  4. security

When to use blockchain?

blockchain is not a silver bullet, so use it when :

  1. The data stored has not to be modified ( proof of existence )
  2. The data cannot be denied by its owner ( non-repudiation)
  3. You want decentralization
  4. You want one source of truth
  5. You want high security
  6. You don’t care about speed ( eg. bitcoin takes 10 min 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, blockchain can be used in different sectors:

  • Real estates: Land ownership
  • Healthcare: Record securely the patient’s data
  • Finance: Reduce the taxes and intermediaries, anti-money laundering, cross border payment
  • Supply chain: Track articles from the vendors to the customers ( Authenticity, 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)
  • Crypto-currency exchange
  • Voting mechanism

Blockchain platforms and applications

  • Bitcoin
  • Ethereum
  • Fabric
  • EOS
  • Chainlink
  • Cardano
  • Etc…

Blockchain types

  • Private: Use only internally and when we know better 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.

“Talk is cheap. Show me the code.”😄

There are two ways to build a blockchain:

  • The easy one is to use the existing pre-built blockchain open-sources like Ethereum, Fabric, EOS, etc… ( maybe I will do one article on this one too)
  • If none of them do fit your requirements then build yours from scratch

In this series, We will build one from scratch so that you can thoroughly understand the blockchain’s state machine.

2. How to build one?

Ok, let’s now create the first baby blockchain in three different programming languages, Go, Python, and Javascript. These prototypes can help you understand the concepts We described earlier.

First, We will create a block, second, We will add the data (header and body) to it, third, We will hash the block, and last but not least We will chain all the blocks up.

A block contains information mentioned earlier, but to simplify things We are going to remove some. let’s delve into the specifics!

In Go

Hope you’re familiar with Go programming as I mentioned earlier, if not try to learn the basics: functions, methods, data types, structures, flow controls, iterations, etc…

Create a folder and add 2 files to 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 packageimport ("fmt")func main(){fmt.Println("I am building my first blockchain") // print thisCreateBlock("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

block.go

package mainimport ("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}

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, ./go on Linux, and Macbook.

Nday Kabulo Sinai

We just created a simple Go program that calls a function and passes some string data. Let’s go ahead and do more nice things. let’s add 2 more files, blockchain.goand structures.go so now we have 4 files: main.go, block.go, structures.go, and blockchain.go

I will add to each line of code some comments in order for you to understand what I am doing.

structures.go

block.go

blockchain.go

main.go

Let’s run it now, go build then .\go

Result: by Nday Sinai

Voila! Easy right?

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))

Let’s save the code and run it again, go buildthen ./go

Final result: by Nday Sinai

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.

All done! congratulations, you just created your baby blockchain in Go😉

In the next episodes, We will gradually fulfill the blockchain requirements. Blockchain is a masterpiece that needs to be engineered the way it’s supposed to be.

Click here for the Javascript version.

“A Blockchain Engineer is a professional who understands thoroughly the principles of blockchain, security, and software engineering for designing, development, maintenance, testing, and evaluation of blockchain core engines and software whereas Blockchain Developer is a professional who builds software on the blockchain that runs across various types of computer. Most blockchain developers use open blockchain platforms and frameworks like ethereum, hyperledger fabric, EOS, etc…”

Which one do you want to be?

In case you find any typos or error when running the code, reach out to me:

LinkedIn: Sinai Nday Kabulo

Insta : sinai_nk

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store