Python Implementation of a Simple Blockchain



By ATS Staff - June 10th, 2025

Blockchain   Python Programming  Software Development  

The example below includes a basic blockchain structure with blocks containing an index, timestamp, data, previous hash, and a proof-of-work mechanism for mining. The code is designed to be beginner-friendly while demonstrating core blockchain concepts like immutability and hashing.

import hashlib
import time
import json

class Block:
    def __init__(self, index, timestamp, data, previous_hash, nonce=0):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.nonce = nonce
        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,
            "nonce": self.nonce
        }, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

class Blockchain:
    def __init__(self, difficulty=4):
        self.chain = []
        self.difficulty = difficulty  # Number of leading zeros required in hash
        self.create_genesis_block()

    def create_genesis_block(self):
        genesis_block = Block(0, time.time(), "Genesis Block", "0")
        self.mine_block(genesis_block)
        self.chain.append(genesis_block)

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

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

    def mine_block(self, block):
        target = "0" * self.difficulty
        while block.hash[:self.difficulty] != target:
            block.nonce += 1
            block.hash = block.calculate_hash()
        print(f"Block mined! Nonce: {block.nonce}, Hash: {block.hash}")

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

            # Verify current block's hash
            if current_block.hash != current_block.calculate_hash():
                print(f"Invalid hash in block {i}")
                return False

            # Verify previous block's hash
            if current_block.previous_hash != previous_block.hash:
                print(f"Chain broken at block {i}")
                return False

            # Verify proof of work
            if current_block.hash[:self.difficulty] != "0" * self.difficulty:
                print(f"Invalid proof of work in block {i}")
                return False

        return True

# Example usage
if __name__ == "__main__":
    my_blockchain = Blockchain(difficulty=4)

    print("Adding Block 1...")
    my_blockchain.add_block({"transaction": "Alice pays Bob 10 BTC"})

    print("\nAdding Block 2...")
    my_blockchain.add_block({"transaction": "Bob pays Charlie 5 BTC"})

    print("\nBlockchain valid?", my_blockchain.is_chain_valid())

    # Print the blockchain
    for block in my_blockchain.chain:
        print(f"\nBlock #{block.index}")
        print(f"Timestamp: {block.timestamp}")
        print(f"Data: {block.data}")
        print(f"Previous Hash: {block.previous_hash}")
        print(f"Hash: {block.hash}")
        print(f"Nonce: {block.nonce}")

    # Test tampering with the blockchain
    print("\nTampering with Block 1...")
    my_blockchain.chain[1].data = {"transaction": "Alice pays Bob 100 BTC"}
    print("Blockchain valid after tampering?", my_blockchain.is_chain_valid())

How It Works

  1. Block Class: Represents a single block in the chain, containing:
  • Index: Position in the blockchain.
  • Timestamp: When the block was created.
  • Data: Transaction or other information (e.g., "Alice pays Bob 10 BTC").
  • Previous Hash: Links to the previous block’s hash for immutability.
  • Nonce: Used in proof-of-work to find a valid hash.
  • Hash: A SHA-256 hash of the block’s contents.
  1. Blockchain Class: Manages the chain of blocks:
  • Initializes with a genesis block (first block).
  • Adds new blocks with data and mines them using proof-of-work.
  • Validates the chain by checking hashes and proof-of-work.
  1. Proof-of-Work: Simulates mining by requiring the block’s hash to start with a set number of zeros (controlled by difficulty). The nonce is incremented until a valid hash is found.
  2. Validation: Ensures the chain’s integrity by verifying:
  • Each block’s hash is correct.
  • Each block’s previous hash matches the prior block’s hash.
  • Each block meets the proof-of-work requirement.

Running the Code

  • Save the code in a file (e.g., blockchain.py).
  • Run it using Python: python blockchain.py.
  • The program creates a blockchain, adds two sample blocks, prints the chain, and tests tampering to demonstrate immutability.

Notes

  • This is a simplified blockchain for educational purposes. Real-world blockchains (e.g., Bitcoin) include additional features like cryptographic signatures, decentralized networks, and consensus mechanisms beyond proof-of-work.
  • The difficulty level (difficulty=4) can be increased for more mining effort, but this will slow down block creation.
  • The code uses SHA-256 for hashing, a standard in blockchain technology.




Popular Categories

Agile 2 Android 2 Artificial Intelligence 52 Backup Tools 2 Blockchain 2 Cloud Storage 5 Code Editors 2 Computer Languages 13 Cybersecurity 9 Data Science 19 Database 10 Digital Marketing 3 Ecommerce 4 Email Server 2 Finance 3 Google 6 HTML-CSS 2 Industries 6 Infrastructure 4 iOS 3 IoT 1 Javascript 6 Latest Technologies 45 Linux 10 LLMs 11 Machine Learning 32 Maths & Stats 1 Mobile 3 MySQL 3 Open source 1 Operating Systems 7 PHP 2 Postgres 1 Project Management 3 Python Programming 28 Rust 1 SEO - AEO 5 Software Development 50 Software Testing 4 Web Server 8 Work Ethics 2
Recent Articles
Axum vs. FastAPI: Which Backend Framework Uses Less Server Resources?
Computer Languages

PostgreSQL Optimization Techniques For Backend Engineers
Data Science

Comprehensive Web Application Testing Plan
Software Testing

The Chief AI Officer Role
Artificial Intelligence

PACS vs. CAMT: Decoding the Core Messaging Categories of ISO 20022
Data Science

UFW vs. Firewalld: Firewall Comparison
Cybersecurity

Ubuntu vs. AlmaLinux: Server OS Choice
Linux

A Production-Ready Backup Architecture
Backup Tools

rsync vs rclone vs restic — A Practical, In-Depth Comparison
Backup Tools

A Comprehensive Guide to rsync
Cloud Storage

Tabulator Data Grid
Data Science

ESP32: Capabilities and Practical Project Examples
IoT

Prompt Engineering: Chain-of-Thought vs Tree-of-Thought
Artificial Intelligence

Prompt Engineering: Zero-Shot vs Few-Shot Prompting
Data Science

Lambda Functions in Python Programming
Python Programming

functools in Python Programming
Latest Technologies

MySQL Database Sharding: A Comprehensive Guide to Horizontal Scaling
Database

Database Sharding: Scaling Horizontally for Modern Applications
Database

Best Python Packages to Learn in 2026
Artificial Intelligence

Step-by-Step Guide to Google Play Store Submission
Google

Step-by-Step Guide to App Store Submission
iOS

Google Nano Banana: The AI Image Tool That Took the Internet by Storm
Artificial Intelligence

Best Practices For Software Development Using Google Gemini 2.5 Pro Through Prompt Engineering
Data Science

Email-Based Passcode Authentication: A Secure and User-Friendly Approach
Software Development

AI Hot Topics Mid-2025
Artificial Intelligence

The Top 3 Python Web Frameworks for 2025: Django, FastAPI, and Flask
Python Programming

Best NLP Libraries for Natural Language Processing in 2025
Artificial Intelligence

Python Implementation of a Simple Blockchain
Blockchain

Explain blockchain like I’m a 10-year-old, using simple analogies.
Blockchain

Prompt Engineering: The Art of Communicating with AI
Artificial Intelligence