Is it hard to build a blockchain from scratch?

Episode 3
In Python

This is the third episode in our series on “is it hard to build a blockchain from scratch ?”, please check the first and second episodes to catch up.

To get started we are going to use the figure from the first episode, let’s copy and paste it here.

fig1. Blockchain (by Sinai)

This is our favorite figure, We will be using it quite often to explain the basic concepts of blockchain technology.

In the previous episodes, we built two basic prototypes using Go and Javascript, let’s now build another baby ledger using python one of the fastest-growing and much-loved programming languages.

To recap, a blockchain is a chain of blocks, each block contains some information listed in figure1. Since we are building a baby ledger let’s stay away from complicated terms and mechanisms that will be covered in the future. I will use the comment sign(#) to explain each line of code, remember everything that comes after the # is a comment.

let’s jump right into it!

let’s first import two important libraries

These two libraries are for hashing and timestamping each block that is generated.

Create a class called Block

This class has an initial method that contains all the block information,but there is no any method that returns a block hash, so let’s go ahead and create it under the class Block.

When a blockchain is deployed, it has only one block, the first ever mined block, that first block is called the genesis block, all the following blocks will be added on top of the first one, so let’s create a static method that will return the genesis block.

Each block is followed by the next block, the next block is the recent added block on the chain, we have to declare another static method for returning each new block , let’s create it.

The block is made and the new block method is created, now we need to initialize our blockchain for receiving all incoming blocks.

Only the genesis block is on the chain, let’s add more blocks to our ledger and print it.

Here is the result:

Oops! the block number 1 has a hash of the genesis block that is not shown in our blockchain, it’s up to us to show the genesis block or not, let me show you how you can print its contents. Before the for loop, add these lines :

Here is the final result:

Now the genesis block becomes visible in the ledger.

Congratulations! You just made another baby blockchain in python.

Stay turned for the next advanced concepts😁.

The entire code:

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

LinkedIn: Sinai Nday Kabulo

Insta: sinai_nk

Is it hard to build a blockchain from scratch? was originally published in Data Driven Investor on Medium, where people are continuing the conversation by highlighting and responding to this story.