Friday, August 29, 2025

thumbnail

Create a Personal Blockchain on Python

 ๐Ÿงฑ What You'll Build


A basic blockchain in Python that:


Stores a chain of blocks


Each block contains data, a timestamp, and a hash


Uses SHA-256 for cryptographic hashing


Validates the chain to ensure integrity


✅ Prerequisites


Python 3.x installed


Basic understanding of Python syntax


Familiarity with concepts like lists and dictionaries


๐Ÿงฐ Step 1: Import Required Libraries

import hashlib

import time


๐Ÿ“ฆ Step 2: Create the Block Class

class Block:

    def __init__(self, index, timestamp, data, previous_hash):

        self.index = index

        self.timestamp = timestamp

        self.data = data

        self.previous_hash = previous_hash

        self.hash = self.calculate_hash()


    def calculate_hash(self):

        block_string = f"{self.index}{self.timestamp}{self.data}{self.previous_hash}"

        return hashlib.sha256(block_string.encode()).hexdigest()


⛓️ Step 3: Create the Blockchain Class

class Blockchain:

    def __init__(self):

        self.chain = [self.create_genesis_block()]


    def create_genesis_block(self):

        return Block(0, time.time(), "Genesis Block", "0")


    def get_latest_block(self):

        return self.chain[-1]


    def add_block(self, new_data):

        latest_block = self.get_latest_block()

        new_block = Block(

            index=latest_block.index + 1,

            timestamp=time.time(),

            data=new_data,

            previous_hash=latest_block.hash

        )

        self.chain.append(new_block)


    def is_chain_valid(self):

        for i in range(1, len(self.chain)):

            curr = self.chain[i]

            prev = self.chain[i - 1]


            if curr.hash != curr.calculate_hash():

                print(f"Block {i} has been tampered with.")

                return False


            if curr.previous_hash != prev.hash:

                print(f"Block {i}'s previous hash doesn't match Block {i-1}'s hash.")

                return False


        return True


๐Ÿงช Step 4: Test Your Blockchain

# Create the blockchain

my_blockchain = Blockchain()


# Add some blocks

my_blockchain.add_block("First block after Genesis")

my_blockchain.add_block("Second block")

my_blockchain.add_block("Third block")


# Display the blockchain

for block in my_blockchain.chain:

    print(f"Index: {block.index}")

    print(f"Timestamp: {block.timestamp}")

    print(f"Data: {block.data}")

    print(f"Hash: {block.hash}")

    print(f"Previous Hash: {block.previous_hash}\n")


# Validate the blockchain

print("Blockchain valid?", my_blockchain.is_chain_valid())


๐Ÿง  What’s Happening Behind the Scenes?


Genesis Block: The first block, manually created with no predecessor.


Hashing: SHA-256 ensures that any change in data invalidates the hash.


Chain Integrity: Each block refers to the previous one using previous_hash.


Validation: Checks that no blocks have been tampered with.


๐Ÿ› ️ Optional Add-Ons


You can extend this basic blockchain by adding:


Proof-of-work (mining)


A simple P2P network


Block timestamps in readable format


JSON output for blocks


✅ Summary


You've just built a basic blockchain in Python—a great starting point to understand how technologies like Bitcoin and Ethereum work at a fundamental level.

Learn Blockchain Course in Hyderabad

Read More

Build a Decentralized To-Do List App

Learning Path: From Beginner to Blockchain Pro

From Web2 to Web3: What Developers Should Know

Best Free Resources to Learn Web3

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive