Blog / Others/ Build a Minimal Blockchain in Under 50 Lines of Python Code (Python 3 Implementation)

Build a Minimal Blockchain in Under 50 Lines of Python Code (Python 3 Implementation)

用不到50行Python代码构建最小区块链(Python 3实现)

What is Blockchain?

Blockchain is a distributed database technology that records data in chronological order within containers called "blocks" and links these blocks into an immutable chain using cryptographic methods. Originally known as the underlying technology for cryptocurrencies like Bitcoin, its applications have expanded to finance, supply chain, digital identity, and more.

Core characteristics of blockchain include:

  • Decentralization: Data is not controlled by a single central authority but is maintained collectively by multiple nodes in the network.
  • Immutability: Once data is written into a block and added to the chain, it is nearly impossible to modify or delete.
  • Transparency and Traceability: All transaction records are publicly viewable (on public chains) and can be traced through hash values.

Building a Minimal Blockchain: SnakeCoin

We will implement a simplest blockchain prototype in under 50 lines of Python 3 code, which we'll call SnakeCoin. This example will help you understand the basic structure and working principles of a blockchain.

1. Define the Block Structure

Each block typically contains: index (position), timestamp, data, previous block's hash, and its own hash. We'll use the SHA-256 algorithm to compute the hash.

import hashlib
import datetime

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()

2. Create the Genesis Block

The first block in a blockchain is called the "genesis block." It has no predecessor, so we create it manually.

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

3. Generate Subsequent Blocks

Each new block is generated based on the previous block's information to ensure chain continuity. The linking of hashes is key to blockchain's tamper-resistance.

def generate_next_block(previous_block, data):
    index = previous_block.index + 1
    timestamp = datetime.datetime.now()
    previous_hash = previous_block.hash
    return Block(index, timestamp, data, previous_hash)

4. Create and Run the Blockchain

We store the blockchain in a Python list, starting with the genesis block and adding new blocks sequentially.

# Initialize blockchain
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

# Add 10 new blocks
for i in range(10):
    new_data = f"Block #{i+1} data"
    new_block = generate_next_block(previous_block, new_data)
    blockchain.append(new_block)
    previous_block = new_block
    
    print(f"Block #{new_block.index} added")
    print(f"Hash: {new_block.hash}n")

Output and Verification

Running the code produces output similar to:

Block #1 added
Hash: a1b2c3d4e5f6...

Block #2 added
Hash: b2c3d4e5f6g7...
...

Each new block's hash depends on the previous block's hash, forming a chain. If you try to modify a block's data, its hash changes, invalidating all subsequent blocks' hashes. This mechanism ensures the blockchain's immutability.

Summary and Extensions

SnakeCoin is a minimal educational model that demonstrates core blockchain concepts: blocks, hash chains, and a decentralized ledger. However, a production-grade blockchain requires additional components:

  • Consensus Mechanism: e.g., Proof of Work (PoW) or Proof of Stake (PoS), to determine who can add new blocks.
  • Peer-to-Peer Network: Multiple nodes maintain and validate the blockchain for decentralization.
  • Transaction Validation: Ensures the validity and security of each transaction.
  • Smart Contracts: Automated contract logic executed on the blockchain (e.g., Ethereum).

This simple implementation provides a foundation for deeper understanding of blockchain principles, distributed systems, cryptography, and decentralized application development.

Post a Comment

Your email will not be published. Required fields are marked with *.