Let’s build a Blockchain network and your own Cryptocurrency using Python

A fast way to understand how Blockchain works at a high level

Erick Zhang
8 min readAug 19, 2018

You are reading this article because, like me, you are EXCITED about the rise of blockchain technology. You want to know how Blockchain actually works and get your hands dirty, but you don’t know where to start.

Well, you have come to the right place! In this tutorial, I am going to teach you how to create a blockchain network with your own cryptocurrency using Python!

Now, before we start, let me explain the concept and the structure of blockchain at a high level.

Imagine one day, you and your boss walked into an elevator, and the topic of blockchain comes up. What is the one sentence that you say to make you look like a blockchain expert? Simple,

“Well Blockchain is just a trusted distributed ledger, which has a shared set of business processes and rules across all the members of the network.”

However, make sure that you can elaborate on what you just said and answer any follow-up questions, or else time your response correctly and walk in the opposite direction when the elevator door opens.

To finish what you started with your boss and truly become an expert in blockchain, you will need to understand the basic structure of this technology. In blockchain, data are stored in blocks, which are chained together. As described in the book “Blockchain for Dummies”, each block contains a hash (a digital fingerprint or unique identifier), timestamped batches of recent valid transactions, and the hash of the previous block. The previous block hash links the blocks together and prevents any block from being altered or a block being inserted between two existing blocks. Sounds confusing, right? Don’t worry, after this tutorial you will be known as “The Blockchain guy” in your office.

Before we start…

You need to have some basic understanding of Python and terminal commands. If not, learnpython.org is a great place for you to get started.

Environment set up

  1. Download Python 3.x version (along with pip3) at https://www.python.org/downloads/
  2. cd into your project directory and run the following commands in your terminal.
  3. mkdir blockchain_python && cd blockchain_python
  4. pip3 install hashlib
  5. pip3 install datetime
  6. pip3 install json
  7. pip3 install pprint
  8. Come up with a cool name for your Cryptocurrency. I’m calling mine EZcoin.
  9. Pick your favorite IDE and let the show begin.
  10. Create a new file, and include these libraries.
Import libraries

Iteration 1:

In this iteration, our objectives are to set up a blockchain framework and define the structure of a Block. Don’t be disappointed if you don’t find this interesting. Trust me, it gets better.

Here is the blueprint for our classes:

Blueprint

Blocks are the fundamental component for a blockchain. In this example, each Block will store the following attributes:

  • timeStamp (when the block is created)
  • trans (the transaction data stored within the block)
  • previousBlock (the hash key of the previous block)
  • difficultyIncrement (don’t worry about this for now we will use it later)
  • hash (the block’s own hash key)

When we first create an instance of the Blockchainclass, an empty block has to be generated in order to start the chaining process. We call this block the Genesis Block. There really isn’t anything special about this block other than the representation of your blockchain going live. If you are interested, here is the genesis block for Bitcoin.

Setting up a genesis block is pretty straightforward. You can almost hard code this component.

When a block is generated, it comes with its own identity ID called the hash key. In this example we will use the SHA-256 protocol and generate a unique ID for each block. To ensure each ID is truly unique, we use the time stamp when the block is created and the data that are stored within each block as its input values.

Now that you have created a Genesis Block and your blockchain is live on your business network, new blocks are coming in fast. How do we append new blocks to our blockchain while keeping it immutable? There are two steps that we need to do here.

  1. Get the hash key of the previous Block.
  2. Generate a hash key for the Block that is waiting to be appended

Note that this is not how blockchain works in real life. Blocks don’t just get added that easily. In this iteration we are simply appending blocks without performing the Proof of Work consensus. Don’t worry about it if you haven not heard of this word before, just it keep it in mind as I will explain it during our second iteration.

Just like that, we have finished the first iteration of our blockchain. It is time to run it against the terminal and take it out for a spin.

  • At line 36, an instance of the Blockchain are created called “EZCoinBlockchain”
  • From lines 37 to 40, two blocks are created and added to the Blockchain

Here is a screenshot of the output that you should receive after running the python script.

As you can see each block in the blockchain successfully stored the hash key of its previous block.

Iteration 2

Now that you have a better understanding of the blockchain structure, let us implement the famous Proof of Work consensus and miners.

If you are new to blockchain, consensus and Proof of Work(PoW) are the two terms that you absolutely need to know to make you sound cool. At a very high level, consensus is the set of rules and guidelines people follow in order to submit a new block to the blockchain. Different blockchain network use different consensus methods as they all have their pros and cons.

To help you better understand consensus, here is a little passage from Aleksandr Bulkin in his article Explaining blockchain — how proof of work enables trustless consensus:

Consider what happens when people talk to each other. If I say “please pass the salt”, I know that what I mean to convey is the desire to receive the salt shaker. When you hear those words you also understand that this is their meaning. However there is more to this. Implicitly, you understand that I understand that this is the meaning and, furthermore I understand that you understand that I understand this. Imagine that I am in a country where English is not commonly spoken. I will most likely not say these words, not because they suddenly stop meaning what I know they mean, but because I no longer have assurance of our mutual consensus around the meaning — I no longer know that you know what I mean.

What we are going to implement today is the PoW consensus and in PoW, miners solve hard, useless problems to create blocks. For instance, in this tutorial a block will NOT be created unless its hash key starts with five consecutive “9”s. This might not look hard, but it took my computer 10 seconds just to generate 2 blocks. Imagine how long it will take once I increase the number of 9s or enforce this rule at different parts of the hash. This is not an accurate representation of a secured PoW consensus, but it does show you how consensus is achieved and upheld within a blockchain network.

A hash key example

Continuing from our previous iteration, let’s first implement a helper function within the Blockchain to help us ensue the validity of our blockchain.

All we are doing here is ensuring that each block is storing the correct hash key of the previous block. Since we designed our hash key to be based on the data within the block, if a hacker decided to change any of its data then a new hash key will be generated for that block. At this point, isChainValid will no longer return true as the hash key of the hacked block does not match what the next block had stored. In order for the blockchain to be valid again, the hacker needs to change every block after the modified block to cover his tracks. This is still insufficient; since the blockchain is a distributed ledger(meaning that everyone who is using your blockchain has a copy of all the transactions) across all the members of the network, the hacker still needs access into at least 51% of the member’s systems, and change their local copy of the blockchain as well. This is called the 51% attack and is almost impossible to achieve, hence why blockchain is a secure technology.

So far we are assuming that each block contains only one transaction. However, this is not the case for most of the blockchains out there. In Bitcoin, a block can contain up to thousands of transactions depending on the size of the block and the time.

What we are going to do now is to create a new class called Transaction and an empty list within the Blockchainclass to store all of the pending transactions.

As a miner/block adder, what’s the incentive for them to solve useless problems all day while paying for an expensive electricity bill? Well, the system is designed to reward the miners whenever they solve a problem, which is appending a block onto the blockchain. In this example, my network will payout 10 EZCoins for whoever solves the hash key.

Finally, the moment we have all been waiting for-Mining! There are two components involved in the mining process:

  • A guess and check mechanism to produce the correct output that satisfies our consensus method.
  • A method to append the block after the consensus is satisfied, and reward the miner.

We will start with the guess and check mechanism first:

The variable difficulty allows the system to control the block generating speed. Computers are getting faster, and we as blockchain developers need to monitor this process and ensure that hackers will not be able to compute everything in a short amount of time.

As mentioned earlier, this is verification method is simply a guess and check mechanism. difficultyIncrement is an arbitrary number that we feed into the calcualteHash function; it will continue to change until the consensus, in this case is 5 consecutive “9”s, is met. Below is the complete Blockclass implementation.

Now that we have a basic mining process, we then need to improve our appendNewBlock method from iteration 1 to slow down our block creating time.

This function creates a new block that takes in all the pending transactions as its data and asks the miner to solve its hash key given a difficulty level. As soon as the block is created and appended, a system generated transaction should be issued and added to the new pendingTransction list.

Last but not least, the blockchain needs to provide everyone with a means to create an transaction and to check their account balance.

Congratulations! You’ve just built your own blockchain and its own currency.

Below is the full script of our final iteration and the output of its testing values. Feel free to play around with code, change the difficulty level, set a transaction limit for each block or even change the blockchain to a PoS consensus method. It’s your blockchain now.If you want to see more information in the console, here is the source code for this project.

If you’d like to get more technical and develop your own private blockchain business network, you can view the original Bitcoin whitepaper here and try out the Hyperledger composer. Best of luck and happy hacking!

Output

--

--