How to Create a Simple Blockchain in Python

In this article, we will explore how to build a simple blockchain using Python, step by step. This demonstration project is useful for understanding the fundamental concepts behind how blockchains work: block structure, hashing, proof of work, and chain validation.

1. Basic Structure

A blockchain is a linked list of blocks, each containing data, a hash of the previous block, and its own hash.


import hashlib
import time

class Block:
    def __init__(self, index, previous_hash, timestamp, data, nonce=0):
        self.index = index
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.data = data
        self.nonce = nonce
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        value = f"{self.index}{self.previous_hash}{self.timestamp}{self.data}{self.nonce}"
        return hashlib.sha256(value.encode()).hexdigest()

2. Creating the Blockchain

Now let's build a Blockchain class that manages the chain of blocks and contains the logic for adding new blocks.


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

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

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

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

3. Proof of Work

To make the blockchain secure, we implement a simple proof of work algorithm that requires the block to have a hash with a number of leading zeros defined by the difficulty.


    def proof_of_work(self, block, difficulty):
        target = "0" * difficulty
        while block.hash[:difficulty] != target:
            block.nonce += 1
            block.hash = block.calculate_hash()
        return block

4. Chain Validation

Finally, we can add a function to verify the integrity of the blockchain.


    def is_chain_valid(self):
        for i in range(1, len(self.chain)):
            current = self.chain[i]
            previous = self.chain[i - 1]

            if current.hash != current.calculate_hash():
                return False

            if current.previous_hash != previous.hash:
                return False

        return True

5. Example Usage

Let's put everything together and create a new blockchain, adding blocks with proof of work.


my_blockchain = Blockchain()
difficulty = 4

data_list = ["Transaction 1", "Transaction 2", "Transaction 3"]

for data in data_list:
    new_block = Block(len(my_blockchain.chain), "", time.time(), data)
    valid_block = my_blockchain.proof_of_work(new_block, difficulty)
    my_blockchain.add_block(valid_block)

print("Is blockchain valid?", my_blockchain.is_chain_valid())

Conclusion

In this example, we implemented a simple blockchain in Python, including proof of work and chain validation. Although simplified, this implementation helps to understand the basic principles that make a blockchain secure.

Back to top