Building a Python blockchain program
The user wants to create a simple blockchain implementation in Python. They didn't ask for a conceptual intro, so I need to focus on the code. I think they want a minimal blockchain example that includes essential features like a block with an index, timestamp, data, previous hash, and hash, along with optional proof-of-work. It would be helpful to provide a single-file script that can create a genesis block and add more blocks, possibly featuring a simple command-line interface.Implementing a blockchain in Python
I can create a Block class that initializes with properties like index, previous hash, timestamp, data, and a nonce. The calculate_hash method computes the hash of the block. Next, I'll build a Blockchain class that starts with a genesis block and allows adding new blocks, mining them by adjusting the nonce until the hash meets the difficulty target. In the main function, I can demonstrate mining blocks and print out the details of each one. I'll also consider using json.dumps for better data handling.Creating educational blockchain code
I want to emphasize that this implementation is for educational purposes and not secure. Since the user requested a simple blockchain program, I'll include comments within the code for clarity. My plan is to use a markdown format with a Python code block. It’s fine to not add lengthy explanations, but I’ll ensure the code is correct and includes timestamps properly by importing time. When hashing the block data, I’ll convert it to JSON for consistency, using json.dumps for replicability in the calculate_hash method.Implementing a Block class
I'll go with a standard class instead of a dataclass for simplicity, ensuring I don't introduce any unnecessary bugs. The Block class will include attributes like index, previous hash, timestamp, data, nonce, and hash, ensuring the hash is computed if not provided. Testing the code in my head, I want to create a genesis block to verify the hash computation. When crafting my response, I'll start with a concise description, present the code, and briefly explain how to run it, avoiding fluff for clarity. Below is a complete, self‑contained Python script that implements a very simple blockchain with:
- A
Block class
- A
Blockchain class
- Basic proof‑of‑work mining
- Chain validation
import time
import hashlib
import json
class Block:
def __init__(self, index, previous_hash, timestamp, data, nonce=0):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data # can be any JSON-serializable object
self.nonce = nonce
self.hash = self.calculate_hash()
def calculate_hash(self):
"""
Create a SHA-256 hash of the block's contents.
"""
block_content = {
"index": self.index,
"previous_hash": self.previous_hash,
"timestamp": self.timestamp,
"data": self.data,
"nonce": self.nonce,
}
block_string = json.dumps(block_content, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
def __repr__(self):
return (
f"Block(index={self.index}, "
f"hash={self.hash[:10]}..., "
f"prev_hash={self.previous_hash[:10]}..., "
f"nonce={self.nonce}, "
f"data={self.data})"
)
class Blockchain:
def __init__(self, difficulty=4):
self.difficulty = difficulty # number of leading zeros required in hash
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
"""
Create the first block in the chain (genesis block).
"""
return Block(
index=0,
previous_hash="0",
timestamp=time.time(),
data="Genesis Block"
)
def get_latest_block(self):
return self.chain[-1]
def mine_block(self, block):
"""
Simple proof-of-work algorithm:
increment nonce until hash has required number of leading zeros.
"""
target_prefix = "0" * self.difficulty
while not block.hash.startswith(target_prefix):
block.nonce += 1
block.hash = block.calculate_hash()
def add_block(self, data):
"""
Create a new block, mine it, and add it to the chain.
"""
previous_block = self.get_latest_block()
new_block = Block(
index=previous_block.index + 1,
previous_hash=previous_block.hash,
timestamp=time.time(),
data=data
)
self.mine_block(new_block)
self.chain.append(new_block)
def is_chain_valid(self):
"""
Verify that the chain is valid:
- Each block's hash is correct.
- Each block points to the correct previous hash.
- Each block's hash satisfies the proof-of-work requirement.
"""
for i in range(1, len(self.chain)):
current = self.chain[i]
previous = self.chain[i - 1]
# Recalculate the hash and compare
if current.hash != current.calculate_hash():
print(f"Block {i} has invalid hash")
return False
# Check previous hash link
if current.previous_hash != previous.hash:
print(f"Block {i} has invalid previous hash link")
return False
# Check proof of work
if not current.hash.startswith("0" * self.difficulty):
print(f"Block {i} does not meet difficulty requirement")
return False
return True
def main():
# Create a new blockchain
my_chain = Blockchain(difficulty=4)
print("Mining block 1...")
my_chain.add_block({"from": "Alice", "to": "Bob", "amount": 10})
print("Mining block 2...")
my_chain.add_block({"from": "Bob", "to": "Charlie", "amount": 5})
print("Mining block 3...")
my_chain.add_block({"from": "Charlie", "to": "Dave", "amount": 2})
# Print the full chain
print("\nBlockchain:")
for block in my_chain.chain:
print(block)
# Validate the chain
print("\nIs blockchain valid?", my_chain.is_chain_valid())
if __name__ == "__main__":
main()
How to use:
- Save this as
simple_blockchain.py.
- Run with:
python simple_blockchain.py
- You’ll see mining progress and the printed blocks, plus a validity check at the end.
If you want, I can extend this with a simple REST API (using Flask/FastAPI) so you can interact with the blockchain over HTTP.