Project Title: Create a Simple Blockchain from Scratch
Age Group: High School (14-18 years)
Project Type: Computer Science (Technology)
Project Overview
In this exciting project, we’ll be diving into one of the hottest topics in technology today: Blockchain. You’ll learn the basic concepts behind how blockchains work and write your very own blockchain from scratch using Python. No prior blockchain knowledge is required, but a basic understanding of Python programming will help.
By the end of the project, you’ll understand how blockchain technology works, why it’s secure, and how it’s used in real-world applications like cryptocurrencies.
Learning Objectives (STEM Process)
- Science: Understand the core principles of decentralized systems and cryptography.
- Technology: Write and test Python code to create a working blockchain.
- Engineering: Develop a structured approach to implementing new blocks and validating transactions.
- Mathematics: Explore how hashes and cryptographic functions ensure security in blockchains.
What You’ll Need
- A computer with Python installed.
- Basic Python programming skills (loops, functions, dictionaries).
- Access to a terminal or Python-friendly IDE (e.g., PyCharm, VSCode, or Anaconda Jupyter Notebook).
- Enthusiasm to learn!
Setup & Requirements
- Install Python: If you don’t have Python installed, go to python.org and download the latest version for your operating system.
- Install Required Libraries: We will use the
hashlib
library to generate hashes, which is a built-in library in Python. No need to install it separately. However, make sure your Python environment is set up and working by running:
python --version
Step-by-Step Instructions
1. What is a Blockchain?
Before we start coding, it’s essential to understand what a blockchain is. A blockchain is essentially a chain of blocks that contain data. Each block has:
- Index: Its position in the chain.
- Timestamp: When the block was created.
- Data: The information stored in the block (e.g., transactions).
- Previous Hash: The hash of the previous block in the chain.
- Hash: A unique identifier created by applying a cryptographic function to the block’s contents.
Each block is cryptographically linked to the one before it, ensuring that once data is added to the blockchain, it’s immutable (cannot be changed).
2. Let’s Code the Blockchain
We’ll now code a simple blockchain in Python.
Step 1: Define the Block Class
Start by creating a Block
class. This will represent each individual block in the chain.
import hashlib
import time
class Block:
def __init__(self, index, previous_hash, data, timestamp=None):
self.index = index
self.previous_hash = previous_hash
self.data = data
self.timestamp = timestamp or time.time()
self.hash = self.calculate_hash()
def calculate_hash(self):
block_string = f"{self.index}{self.previous_hash}{self.data}{self.timestamp}".encode()
return hashlib.sha256(block_string).hexdigest()
__init__
: Initializes the block with its index, data, previous hash, and timestamp. It also calculates its own hash.calculate_hash
: This method generates a cryptographic hash of the block’s content using SHA-256 (Secure Hash Algorithm).
Step 2: Define the Blockchain Class
Now that we have a block, let’s create the actual blockchain.
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, "0", "Genesis Block")
def get_latest_block(self):
return self.chain[-1]
def add_block(self, new_block):
new_block.previous_hash = self.get_latest_block().hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)
__init__
: Initializes the blockchain with the genesis block (the first block).create_genesis_block
: Creates the very first block in the chain with fixed data (“Genesis Block”).get_latest_block
: Retrieves the most recent block in the chain.add_block
: Adds a new block to the chain, updates itsprevious_hash
, and recalculates its hash to maintain integrity.
Step 3: Testing the Blockchain
Let’s now create a small test function to see the blockchain in action.
def main():
# Initialize blockchain
blockchain = Blockchain()
# Add new blocks
blockchain.add_block(Block(1, blockchain.get_latest_block().hash, "Block 1 Data"))
blockchain.add_block(Block(2, blockchain.get_latest_block().hash, "Block 2 Data"))
# Print blockchain details
for block in blockchain.chain:
print(f"Block {block.index}:")
print(f"Data: {block.data}")
print(f"Hash: {block.hash}")
print(f"Previous Hash: {block.previous_hash}\n")
if __name__ == "__main__":
main()
blockchain.add_block(...)
: Adds new blocks to the blockchain with simple data.- The loop prints out each block’s details, showing how each block is linked to the previous one via its hash.
Output Example
When you run the code, it should print out something like:
Block 0:
Data: Genesis Block
Hash: 7f69c58f0f78ef16e7e315e517206eb257c78825ae8817dfc9e12a31edb4f639
Previous Hash: 0
Block 1:
Data: Block 1 Data
Hash: d9e07d0933a09bce8b508953bd0d43d5a3ed2da5b7be801f571c81d1d1e73b4e
Previous Hash: 7f69c58f0f78ef16e7e315e517206eb257c78825ae8817dfc9e12a31edb4f639
Block 2:
Data: Block 2 Data
Hash: 4313e7a15508f93b46cbf45a6eb13c9c28d523e17d7f6dcaa3a19148d403baff
Previous Hash: d9e07d0933a09bce8b508953bd0d43d5a3ed2da5b7be801f571c81d1d1e73b4e
Each block links back to the previous one using the previous hash field, creating a secure chain.
Advanced Features (Optional)
Once you’ve built your basic blockchain, here are some cool features you can add:
- Proof of Work (Mining): Implement a mining system that requires blocks to meet a certain condition (e.g., their hash must start with a specific number of zeroes) before being added. Example of Proof of Work:
def mine_block(self, difficulty):
required_prefix = '0' * difficulty
while not self.hash.startswith(required_prefix):
self.timestamp = time.time() # Change something in the block to affect the hash
self.hash = self.calculate_hash()
- Transaction System: Instead of just adding blocks with static data, create a system where users can make transactions that are stored in the blocks.
Testing and Verifying Your Blockchain
- Integrity Check: Try tampering with a block’s data and rerun the chain to see how it breaks the cryptographic link between blocks. Example:
blockchain.chain[1].data = "Tampered Data"
After this change, the hashes will no longer match, and the chain will become invalid, demonstrating how blockchains are immutable.
- Extend the Chain: Keep adding blocks with real-world data (e.g., simple transactions) and see how the blockchain grows.
Conclusion
You’ve just built a simple yet powerful blockchain from scratch! You now understand the building blocks (pun intended) of this revolutionary technology that powers things like cryptocurrencies, secure data sharing, and even smart contracts.
Next Steps
In future posts, we’ll dive deeper into more advanced features like Proof of Work and smart contracts. Stay tuned to the Future Innovators series for more cutting-edge STEM projects!
Feel free to test this code, tweak it, and build your own blockchain projects. Keep innovating!
Subscribe to our email newsletter to get the latest posts delivered right to your email.
Comments