How to create a Blockchain in Python

Vaibhav Shukla
Geek Culture
Published in
7 min readNov 26, 2021
Picture Credit: Pierre Borthiry on Unsplash

So yeah! now it’s down to you and me, discussing the hottest, popular, clichéd topic on the internet. It’s ok if you’ve heard the term before and you feel a bit insecure because you kind of don’t get what exactly it is.

Anyways, let’s discuss ‘Blockchain’. And answer some questions like, What is a Blockchain? How does it work? How is it different? What problem does it solve? and Why I should care about this?

I’ve answered a BONUS question at the end of the article, so make sure you read the whole article. Bee-whoop!!!

What is a Blockchain?

It’s the underlying technology that many cryptocurrencies are based on and it is considered one of the most important inventions in the 21st century.

According to Google:

“A system in which a record of transactions made in bitcoin or another cryptocurrency are maintained across several computers that are linked in a peer-to-peer network.”

According to Me:

A linear chain of BLOCKS, and each BLOCK contains some information. The chain is immutable, which means no one can sneak in between and change the data in any of the blocks.

Mine was slightly easier right? 😄

How does it work?

Blockchain, as its name implies, is formed by multiple blocks linked together in a chain.

Each block normally contains the following information:

  • Data: this could be anything like transaction data.
  • Hash Value: this is basically the ID of the block.
  • Previous Hash Value: this keeps track of the previous block ID. For now, you just need to know that we use this value to form a chain between the current block and the previous block. I will explain why this value is important later on in the article.
  • Timestamp: this tells us when the block is created.
  • Proof of Work: this is a number showing the effort to find the hash value of the current block. If you have heard of mining, this value represents how long it takes (in form of a number) for the machines to calculate the hash value.

In the real world, a block is way more complex than this but I want to keep it simple :)

Let’s jump into the fun part, coding!

Before we start, I want to note that this article will be easier to follow if you know some basic programming. But no worries if you don’t because I will try my best to explain each piece of code in detail.

Let’s create a Blockchain in Python

Import the necessary modules

Let’s import some modules on the top of blockchain.py

Create a Block class

This class accepts 2 arguments. The first one is the hash value of the previous block, and the second one is the data of the current block.

Inside the __init__()function, we initialize the block data with the constructor arguments. We set timeStamp to the current time and proofOfWork to 0.

Remember when I said we need to calculate the hash value? Yes, the hash value is not just a random string, we need to find the current hash value based on both current data and previous hash for security sake.

If a hacker changes the data of a block, they also have to recalculate hash values of all the blocks ahead to make the chain valid (this might take thousands of years if they use the same computer as I do)

For those who don’t know about hashing, it’s basically how we convert our data into a bunch of random characters. For example, the word “hello” could be hashed into “e2d48e7bc…”. Because hashing only works in one direction, it’s easy to find the hash output given the input but it’s super hard to predict the input from the hash output.

Let’s take a look at the calculateHash method.

This function basically generates a hash value based on the combination of the previous hash, current data, current timestamp, and proof of work.

We use the sha256 function from hashlib inbuilt library. This library basically allows us to use several hashing methods. We use Secure Hash Algorithm 256 (SHA 256) in this tutorial. As you can see, we import hash at the top of the file.

Let’s look at the final function of the Block class. The mine function.

This mine the function keeps increasing proofOfWork until we found a hash starting with our desired number of 0 (we called it difficulty). The higher difficulty is, the longer it takes for the hash to be created. This is because the only way to find the input from the hash output is to try different inputs one by one.

The next part is creating the Blockchain to store all the blocks.

Creating a Blockchain class

Let’s create a Blockchain class

Our Blockchain store 1 array called chain . We will also add a genesisBlock to the chain. The genesis block is basically the first block in the chain. Therefore, we could pass “0” as the previous hash value as there’s no previous block.

Next, we will implement addBlock method which adds a new block to the chain.

This function accepts new data as a parameter and creates a new block-based on that data and the previous block’s hash.

Remember when we create a new block, we have to calculate its hash value using the mine function. To make it fast, I only set the diffifulty to 2 so the new hash value must start with 2 zeros.

After finding the hash value, we just need to add the new block to the chain.

Finally, we need isValid function to validate if the current chain is valid or not.

This function basically goes through each block (except the genesis one) and checks if there is any violation in the hash value. It returns true if there is no violation.

Get the latest block

Not a necessity, but you can also add a getLatestBlock method just to get the last block added to the chain.

Congratulation! You have successfully built a blockchain.

Let’s see how it works in the example section below.

Example Usage

If you’ve read till here, I don’t need to explain what Python classes are. Do I?
Just inspect the printed class object and implement it in your recent projects.

That’s it, now go and show off your friends saying what you guys are discussing, I can build that!

But wait, there’s more…

What problem does it solve?

The biggest and most mainstream problem which it solves is that it provides a decentralized platform for data sharing.

Above is the demonstration of a CENTRALIZED and DECENTRALIZED network infrastructure.

Apart from this, and also because of this… blockchain solves the issue of
storage and security,
data transfer — will be faster,
e-voting, charity, crowdfunding — will be a lot easier (as no one is controlling the flow)

Why should I care about this?

Just answer me this:

  • When was the last time you cared about how do the payment gateway of XYZ bank works?
  • How does Google authenticate its user over third-party services?
  • Ever thought about how/where Instagram stores its data?

If you can’t answer any of these, there is no need to know anything about blockchain. I mean you can, but there is no NEED to.

Just like you don’t need to know JavaScript to be able to use Instagram. You don’t need Blockchain to be able to invest in Bitcoin.

Now the BONUS time.

Blockchain is not Bitcoin

If are a Python guy, you might have noticed that the above heading is a legit code statement😅

Basically, the point I’m making is that Blockchain is a technology that has a lot of potentials if you use it wisely.

One can make almost anything based on the implementation of Blockchain. From cryptocurrency to cloud storage, social media, search engines and a heck of a lot of stuff.

Let’s not saturate and limit Blockchain to JUST bitcoin.

Blockchain is a technology based on cryptography.
Bitcoin is a cryptocurrency built using Blockchain.

Thanks for reading, if you find this article helpful, you can give it a clap.
I would appreciate a follow too :)

--

--

Vaibhav Shukla
Geek Culture

20 years old Indian Software Developer. IG— @mrvaibh0