Building a blockchain

In this tutorial, I am going to show you how to create your own basic blockchain.

If you haven't already checked out our lesson on blockchain basics, I recommend you do that before this tutorial

This tutorial is aimed at people with at least some knowledge in Python.

Things we need:

You will need to have Python 3.6 or higher along with pip installed. To install Python click here

We are going to create this blockchain in 3 steps.

  1. Building a blueprint for the blockchain
  2. Adding a new transaction to the blockchain
  3. Creating new blocks

Let's get building!

Step 1 - Building a blueprint for the blockchain

Open your favorite text editor or IDE, I personally use Pycharm but any editor will do.

Create a new Python file and save it as blockchain.py

Below we will create our blockchain blueprint.

The first step is to create a blockchain class, this class will be an empty list in which we will store our blockchain in.

class Blockchain(object):
    def __init__(self):
        self.chain = []
        self.current_transactions = []

    def new_transaction(self):
        # Adds a new transaction to the list of transactions
        pass

    def new_block(self):
        # Creates a new Block and adds it to the chain
        pass

    def proof_of_work():
       #  Simple Proof of Work Algorithm
       pass


     @property
    def last_block(self):
        return self.chain[-1]


    @staticmethod
    def hash(block):
    # creates a SHA-256 hash of a block
       pass

As you see above most of the defs have a pass in them, Everything we do in this Tutorial will be based on this blueprint, so as we move through the tutorial you will just have to take the new code and replace the PASS section within the corresponding def.

Step 2 - Adding a new transaction to the blockchain

We need a way of adding transactions to a Block. Our new_transaction() method is responsible for this:


    def new_transaction(self, sender: str, recipient: str, amount: int) -> int:
        """
        Creates a new transaction to go into the next mined Block
        :param sender: Address of the Sender
        :param recipient: Address of the Recipient
        :param amount: Amount
        :return: The index of the Block that will hold this transaction
        """
        self.current_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount,
        })

        return self.last_block['index'] + 1

After new_transaction() adds a transaction to the list, it returns the index of the block which then sends the new transaction to the block, and will be the next one to be mined. This will be useful later on, to the user submitting the transaction.

Step 3 - Creating new blocks

When our Blockchain is instantiated we’ll need to seed it with a genesis block with no predecessors.

A genesis block is the first block of a block chain

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 and proof of work shortly.

Below we will create the new genesis block:

 def new_block(self, proof: int, previous_hash: Optional[str]) -> Dict[str, Any]:
        """
        Create a new Block in the Blockchain
        :param proof: The proof given by the Proof of Work algorithm
        :param previous_hash: Hash of previous Block
        :return: New Block
        """

        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1]),
        }

        # Reset the current list of transactions
        self.current_transactions = []

        self.chain.append(block)
        return block

What does a block look like?

Each Block has an

  • Index
  • Timestamp (in Unix time)
  • List of transactions
  • Proof
  • A hash of the previous Block

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

block = {
    'index': 1,
    'timestamp': 1506057125.900785,
    'transactions': [
        {
            'sender': "8527147fe1f5426f9dd545de4b27ee00",
            'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
            'amount': 5,
        }
    ],
    'proof': 324984774000,
    'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}

We have now created our very own basic blockchain! In the next lesson you will learn how to mine the blockchain and have hands on interactions with your blockchain.

Click here for the next lesson.

This lesson is based on material from https://github.com/dvf/blockchain which has this licence: https://github.com/dvf/blockchain/blob/master/LICENSE

Sign up to be notified when new lessons arrive!

* indicates required