Building Own Blockchain Using Python

To understand blockchain deeply, the best approach is to build a simple one yourself. Below is a minimal example of a blockchain written in Python. This example focuses on core concepts such as blocks, hashing, and chain validation rather than production-level complexity.

import hashlib
import json
import time

The Block class represents a single block in the blockchain. Each block stores data, a timestamp, the hash of the previous block, and its own hash.

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

    def calculate_hash(self):
        block_string = json.dumps({
            "index": self.index,
            "timestamp": self.timestamp,
            "data": self.data,
            "previous_hash": self.previous_hash
        }, sort_keys=True).encode()

        return hashlib.sha256(block_string).hexdigest()

Now we define the Blockchain class, which manages the entire chain and ensures that new blocks are linked correctly.

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

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

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

    def add_block(self, data):
        previous_block = self.get_latest_block()
        new_block = Block(
            index=len(self.chain),
            data=data,
            previous_hash=previous_block.hash
        )
        self.chain.append(new_block)

You can now create a blockchain instance and add transactions or messages to it.

my_blockchain = Blockchain()
my_blockchain.add_block("First transaction: Alice sends 10 coins to Bob")
my_blockchain.add_block("Second transaction: Bob sends 5 coins to Charlie")

for block in my_blockchain.chain:
    print(vars(block))

This code creates a working blockchain where each block is cryptographically linked to the previous one. Even though it is simple, it demonstrates the fundamental logic used in real-world cryptocurrencies.

From Blockchain to Cryptocurrency

To turn a blockchain into a full cryptocurrency, additional components are required, such as digital wallets, public-private key cryptography, transaction validation, mining or staking mechanisms, and peer-to-peer networking. Mining usually involves solving computational puzzles to secure the network, while staking relies on holding coins to validate transactions.

Smart contracts, tokens, and decentralized applications can also be built on top of blockchains, allowing developers to create financial systems, games, marketplaces, and governance models without centralized control. Modern blockchains expand far beyond payments and are now foundational infrastructure for Web3.

Leave a Reply