Simulating a Blockchain in Python

Mac Lawson, blockchain

Blockchain is a decentralized, distributed ledger that records transactions on multiple computers. Each block in the blockchain contains a hash of the previous block, a timestamp, and transaction data. In this tutorial, we will create a simple blockchain that will store transaction data using Python.


We will start by importing the necessary libraries.

import hashlib
import json
from time import time
from typing import List

Next, we will create a Block class, which will represent a block in the blockchain.

class Block:
    def __init__(self, index: int, timestamp: float, data: str, previous_hash: str):
        self.index = index
        self.timestamp = timestamp = data
        self.previous_hash = previous_hash
        self.hash = self.calculate_hash()

    def calculate_hash(self) -> str:
        block_string = json.dumps(self.__dict__, sort_keys=True)
        return hashlib.sha256(block_string.encode()).hexdigest()

The Block class has five attributes: index, timestamp, data, previous_hash, and hash. The calculate_hash method will take the block’s attributes and create a SHA-256 hash.

Next, we will create a Blockchain class, which will represent the blockchain itself.

class Blockchain:
    def __init__(self):
        self.chain: List[Block] = [self.create_genesis_block()]

    def create_genesis_block(self) -> Block:
        return Block(0, time(), "Genesis Block", "0")

    def get_latest_block(self) -> Block:
        return self.chain[-1]

    def add_block(self, new_block: Block):
        new_block.previous_hash = self.get_latest_block().hash
        new_block.hash = new_block.calculate_hash()

    def is_chain_valid(self) -> bool:
        for i in range(1, len(self.chain)):
            current_block = self.chain[i]
            previous_block = self.chain[i - 1]
            if current_block.hash != current_block.calculate_hash():
                return False
            if current_block.previous_hash != previous_block.hash:
                return False
        return True

The Blockchain class has four methods: create_genesis_block, get_latest_block, add_block, and is_chain_valid. The create_genesis_block method will create the first block in the blockchain, the get_latest_block method will return the latest block in the chain, the add_block method will add a new block to the chain, and the is_chain_valid method will check if the blockchain is valid.


To create a new blockchain and add blocks to it, we can use the following code:

blockchain = Blockchain()
blockchain.add_block(Block(1, time(), "Transaction Data", ""))
blockchain.add_block(Block(2, time(), "Transaction Data", ""))
blockchain.add_block(Block(3, time(), "Transaction Data", ""))

To check if the blockchain is valid, we can use the following code:


This will return True if the chain is valid and False otherwise.


In this tutorial, we have gone through the process of simulating a blockchain in Python. While this is a simplified version of a blockchain, it demonstrates the basic principles behind the technology. With this knowledge, you can now explore more complex implementations of blockchain technology.

About the Author

Mac Lawson is a security researcher with a passion for cryptography and blockchain technology. He enjoys exploring new ways to implement and improve security measures in software development.

© Mac Lawson.RSS