Create a simple blockchain in Python

To learn the basics of how a blockchain work use the Python code below to create a very basic blockchain in Python.

Import hashlib which is a common interface to many different secure hash and message digest algorithms in Python. For more information about hashlib read here.

First create a blockchain class and name for file Block.py. This class is responsible for joining the current transaction information and then hashing this information with the previous blocks hash.

Then create a new file called blockchain which imports the Block.py contents. Each block has contents that gets hashed with the previous blocks hash.

The simple blockchain creates a genesis block (first block), and then second block and so on. This is a great way to step through the orders of operation of a blockchain and see how the previous block impacts the current block.

Name this file Block.py

import hashlib


class block:
    def __init__(self, previous_hash, transactions):
        self.transactions = transactions
        self.previous_hash = previous_hash
        string_to_hash = ''.join(transactions) + previous_hash
        self.block_hash = hashlib.sha256(string_to_hash.encode()).hexdigest()

name this file blockchain.py

from Block import block

blockchain = []

genesis_block = block('this is the first block',['sean sent',
                                                'bryan sent',
                                                'Steve sent'])

second_block = block(genesis_block.block_hash, ['mary sent',
                                               'keira sent'])

third_block = block(genesis_block.block_hash, ['bryan sent',
                                               'fran sent'])


print(genesis_block.block_hash)
print(second_block.block_hash)
print(third_block.block_hash)

Next Review – Convert a string to SHA256 in Python

Leave a Reply