DEV Community

DP Genius
DP Genius

Posted on

How to Build a Simple Blockchain Using Python (Step-by-Step Guide)

Blockchain is one of the most powerful technologies behind cryptocurrencies like Bitcoin and Ethereum. At its core, a blockchain is a distributed, immutable ledger that stores data in blocks linked together using cryptography.

In this article, we will learn how to create a simple blockchain using Python, understand its core concepts, and implement a basic working model. You can check the advantages of Ethereum Blockchain.

What Is a Blockchain?
A blockchain is a chain of blocks where:

  • Each block stores data
  • Each block contains a cryptographic hash of the previous block
  • Once data is added, it cannot be changed easily
  • The system is decentralized and secure

Key Characteristics of Blockchain

  • Decentralized
  • Immutable
  • Transparent
  • Secure
  • Trustless

Core Components of a Blockchain
Before coding, let’s understand the basic components:

Block

  • Index
  • Timestamp
  • Data
  • Hash of previous block
  • Current block hash

Chain

  • A list of blocks
  • Each block links to the previous one

Hash Function

  • Converts data into a fixed-length string
  • Any change in data produces a new hash

Requirements to Build Blockchain in Python

You only need:

  • Python 3.x
  • Basic understanding of Python
  • hashlib library (built-in)
  • datetime library (built-in)

No external libraries are required.

Step 1: Import Required Libraries

import hashlib
import datetime
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Block Class

This class represents a single block in the blockchain.

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()
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • calculate_hash() generates a SHA-256 hash
  • Even a small data change results in a new hash
  • This ensures security and integrity

Step 3: Create the Blockchain Class

This class manages the entire chain.

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

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

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

    def add_block(self, new_data):
        previous_block = self.get_latest_block()
        new_block = Block(
            index=len(self.chain),
            timestamp=datetime.datetime.now(),
            data=new_data,
            previous_hash=previous_block.hash
        )
        self.chain.append(new_block)
Enter fullscreen mode Exit fullscreen mode

Step 4: Create and Use the Blockchain

my_blockchain = Blockchain()

my_blockchain.add_block("First Transaction")
my_blockchain.add_block("Second Transaction")
my_blockchain.add_block("Third Transaction")

Step 5: Display the Blockchain
for block in my_blockchain.chain:
    print("Index:", block.index)
    print("Timestamp:", block.timestamp)
    print("Data:", block.data)
    print("Hash:", block.hash)
    print("Previous Hash:", block.previous_hash)
    print("-" * 50)
Enter fullscreen mode Exit fullscreen mode

How This Blockchain Works

  • Each block contains the hash of the previous block
  • If someone tries to modify a block: -- The hash changes -- All following blocks become invalid
  • This makes tampering extremely difficult

Limitations of This Simple Blockchain
This basic blockchain does not include:

  • Proof of Work (Mining)
  • Proof of Stake
  • Peer-to-peer networking
  • Smart contracts
  • Consensus algorithms

It is designed only for learning purposes.

How to Improve This Blockchain

To build a more advanced blockchain, you can add:

  • Proof of Work (PoW)
  • Transaction validation
  • Wallets & digital signatures
  • Decentralized nodes
  • REST API using Flask
  • Smart contracts

Use Cases of Blockchain

  • Cryptocurrencies
  • Supply chain tracking
  • Digital identity
  • Healthcare records
  • Voting systems
  • Financial transactions

Conclusion

Building a blockchain in Python helps you understand how decentralization, hashing, and immutability work together. Although this is a simplified version, it forms a strong foundation for learning advanced blockchain concepts.

Python is an excellent choice for beginners because of its simplicity and readability.

Top comments (0)