Python Implementation of a Simple Blockchain



By ATS Staff

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 46 Blockchain 2 Cloud Storage 3 Code Editors 2 Computer Languages 11 Cybersecurity 8 Data Science 13 Database 5 Digital Marketing 3 Ecommerce 3 Email Server 2 Finance 2 Google 3 HTML-CSS 2 Industries 6 Infrastructure 2 iOS 2 Javascript 5 Latest Technologies 41 Linux 5 LLMs 11 Machine Learning 32 Mobile 3 MySQL 2 Operating Systems 3 PHP 2 Project Management 3 Python Programming 23 SEO - AEO 5 Software Development 39 Software Testing 3 Web Server 6 Work Ethics 2
Recent Articles
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

Best Generative AI Tools for Code Generation
Artificial Intelligence

TensorFlow vs PyTorch: A Comprehensive Comparison
Artificial Intelligence

Introduction to Keras: A Powerful Deep Learning Framework
Artificial Intelligence

SciPy: The Scientific Computing Powerhouse in Python
Data Science

Scikit-Learn: A Comprehensive Guide to Machine Learning in Python
Data Science

Seaborn: A Powerful Python Library for Data Visualization
Data Science

Streamlit Python: The Ultimate Tool for Building Data Apps Quickly
Data Science

Answer Engine Optimization: The Future of Search Visibility
SEO - AEO

Cybersecurity Resilience: Building a Robust Defense Against Evolving Threats
Cybersecurity

DevSecOps: Integrating Security into the DevOps Pipeline
Data Science

How DevOps is Shaping Modern Teams
Agile

How to Calculate Load Average on a Linux Server
Linux

Agile DevOps Best Practices: Forging Speed and Stability
Agile

Best AI Tools to Generate Python Code
Artificial Intelligence

Manus AI: A New Frontier in Autonomous Intelligence
Artificial Intelligence

Unveiling DeepSeek: The Next Frontier in AI-Powered Search Technology
Artificial Intelligence

The Importance of Good Work Ethics: Building a Foundation for Success
Work Ethics

The Power of Teamwork: Achieving Success Together
Work Ethics

Modern Web Design: Crafting the Digital Experience
Latest Technologies

Python Web Frameworks: A Comprehensive Guide
Python Programming

How to Secure a Website or a Particular Subdirectory Using Apache Web Server
Web Server

Transformative AI: Revolutionizing the World One Innovation at a Time
Artificial Intelligence

An Introduction to LangChain: Building Advanced AI Applications
Artificial Intelligence

What is a Vector Database?
Database

What is Artificial Intelligence?
Artificial Intelligence

VSCode Features for Python Developers: A Comprehensive Overview
Python Programming

Understanding Python Decorators
Python Programming