i Building the simple blockchain – All things in moderation

Building the simple blockchain

We’re all heard too much about bitcoin, ethereum and others on the media. And the technology behind all them is blockchain. So what is this ? How can a build one ? These questions is strugged me and I deciced gooogle about it, I found a good article guide everyone with basic about python can build the blockchain. This post I write follow the post I mentioned above by my way.

What is blockchain ?
A blockchain is a digital ledger of records that’s arranged in chunks of data called blocks. These blocks then link with one another through a cryptographic validation known as a hashing function. Linked together, these blocks form an unbroken chain-a *blockchain.

Step 1: Building a Blockchain

Open up your favourite text editor or IDE, personally I prefer PyCharm or visual studio code. Create a new file, called blockchain.py. We’ll only use a single file, but if you get lost, you can always refer to the source code.

Representing a Blockchain

We’ll create a Blockchain class whose constructor creates an initial empty list (to store our blockchain), and another to store transactions. Here’s the blueprint for our class:

Our Blockchain class is responsible for managing the chain. It will store transactions and have some helper methods for adding new blocks to the chain. Let’s start fleshing out some methods.

What does a Block look like?

Here’s an example of what a single Block looks like:

Each Block has an index, a timestamp (in Unix time), a list of transactions, a proof (more on that later), and the hash of the previous Block.

Adding Transactions to a Block

After new_transaction() adds a transaction to the list, it returns the index of the block which the transaction will be added to—the next one to be mined.

Creating new Blocks

When our Blockchain is instantiated we’ll need to seed it with a genesis block—a block with no predecessors. We’ll also need to add a “proof” to our genesis block which is the result of mining (or proof of work). We’ll talk more about mining later.

In addition to creating the genesis block in our constructor, we’ll also flesh out the methods for new_block(), new_transaction() and hash():

Understanding Proof of Work

A Proof of Work algorithm (PoW) is how new Blocks are created or mined on the blockchain. The goal of PoW is to discover a number which solves a problem. The number must be difficult to find but easy to verify—computationally speaking—by anyone on the network. This is the core idea behind Proof of Work.

We’ll look at a very simple example to help this sink in.

Let’s decide that the hash of some integer x multiplied by another y must end in 0. So, hash(x * y) = ac23dc…0. And for this simplified example, let’s fix x = 5. Implementing this in Python:

from hashlib import sha256

x = 5
y = 0  # We don't know what y should be yet...

while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "0":
    y += 1

print(f'The solution is y = {y}')  

The solution here is y = 21. Since, the produced hash ends in 0:

hash(5 * 21) = 1253e9373e...5e3600155e860  

In Bitcoin, the Proof of Work algorithm is called Hashcash. And it’s not too different from our basic example above. It’s the algorithm that miners race to solve in order to create a new block. In general, the difficulty is determined by the number of characters searched for in a string. The miners are then rewarded for their solution by receiving a coin—in a transaction.

The network is able to easily verify their solution.

Implementing basic Proof of Work

Let’s implement a similar algorithm for our blockchain. Our rule will be similar to the example above:

Find a number p that when hashed with the previous block’s solution a hash with 4 leading 0s is produced.  

Step 2: Our Blockchain as an API

We’re going to use the Python Flask Framework. It’s a micro-framework and it makes it easy to map endpoints to Python functions. This allows us talk to our blockchain over the web using HTTP requests.

We’ll create three methods:

/transactions/new to create a new transaction to a block
/mine to tell our server to mine a new block.
/chain to return the full Blockchain.  

Setting up Flask

Our “server” will form a single node in our blockchain network. Let’s create some boilerplate code:

The Transactions Endpoint

Since we already have our class method for adding transactions to a block, the rest is easy. Let’s write the function for adding transactions:

The Mining Endpoint

Our mining endpoint is where the magic happens, and it’s easy. It has to do three things:

1. Calculate the Proof of Work
2. Reward the miner (us) by adding a transaction granting us 1 coin
3. Forge the new Block by adding it to the chain

Note that the recipient of the mined block is the address of our node. And most of what we’ve done here is just interact with the methods on our Blockchain class. At this point, we’re done, and can start interacting with our blockchain.

Step 3: Interacting with our Blockchain

You can use plain old cURL or Postman to interact with our API over a network.

Fire up the server:
You can clone the final code here and follow the instructions. I preper using docker.

docker run --rm -p 80:5000 blockchain

Let’s try mining a block by making a GET request to http://localhost:5000/mine:

Let’s create a new transaction by making a POST request to with a body containing our transaction structure:

I restarted my server, and mined one blocks, to give 2 in total. Let’s inspect the full chain by requesting http://localhost:5000/chain:

    "chain": [
            "index": 1,
            "previous_hash": "1",
            "proof": 100,
            "timestamp": 1512439280.357809,
            "transactions": []
            "index": 2,
            "previous_hash": "67e35113d59ef2fb6200bccf7c03218c93da201a89c8b051ec0454cf7edcee22",
            "proof": 35293,
            "timestamp": 1512439440.9529784,
            "transactions": [
                    "amount": 1,
                    "recipient": "80afcc39247e44279cb2b8bc7b778107",
                    "sender": "0"
    "length": 2

Step 4: Consensus

This is very cool. We’ve got a basic Blockchain that accepts transactions and allows us to mine new Blocks. But the whole point of Blockchains is that they should be decentralized. And if they’re decentralized, how on earth do we ensure that they all reflect the same chain? This is called the problem of Consensus, and we’ll have to implement a Consensus Algorithm if we want more than one node in our network.

Registering a new Nodes

Before we can implement a Consensus Algorithm, we need a way to let a node know about neighbouring nodes on the network. Each node on our network should keep a registry of other nodes on the network. Thus, we’ll need some more endpoints:

/nodes/register to accept a list of new nodes in the form of URLs.
/nodes/resolve to implement our Consensus Algorithm, which resolves any conflicts—to ensure a node has the correct chain.

We’ll need to modify our Blockchain’s constructor and provide a method for registering nodes:

Implementing the Consensus Algorithm

As mentioned, a conflict is when one node has a different chain to another node. To resolve this, we’ll make the rule that the longest valid chain is authoritative. In other words, the longest chain on the network is the de-facto one. Using this algorithm, we reach Consensus amongst the nodes in our network.

The first method valid_chain() is responsible for checking if a chain is valid by looping through each block and verifying both the hash and the proof.

resolve_conflicts() is a method which loops through all our neighbouring nodes, downloads their chains and verifies them using the above method. If a valid chain is found, whose length is greater than ours, we replace ours.

Let’s register the two endpoints to our API, one for adding neighbouring nodes and the another for resolving conflicts:

At this point you can grab a different machine if you like, and spin up different nodes on your network. Or spin up processes using different ports on the same machine. I spun up another node on my machine, on a different port, and registered it with my current node. Thus, I have two nodes: http://localhost:5000 and http://localhost:5001.

Registering a new Node

I then mined some new Blocks on node 2, to ensure the chain was longer. Afterward, I called GET /nodes/resolve on node 1, where the chain was replaced by the Consensus Algorithm:

Consensus Algorithm at Work

I hope that this has inspired you to create something new. I’m ecstatic about Cryptocurrencies because I believe that Blockchains will rapidly change the way we think about economies, governments and record-keeping.



Leave a Reply