How to Build a Simple Blockchain in Python
Creating a blockchain from scratch can seem intimidating, but with some basic knowledge of Python, you can create a simple version step by step. Let's dive into building a basic blockchain that can be the foundation for something more complex.
What is a Blockchain?
A blockchain is a distributed ledger that records transactions across many computers. This ensures that the recorded transactions cannot be altered retroactively. Each block in a blockchain contains: - A list of transactions - A timestamp - The hash of the previous block - Its own hash
Setting Up Your Environment
Before we dive in, ensure you have Python installed on your system. If not, download it from python.org.
Writing Your First Block
Let's start by creating a class that will allow us to construct blocks. Each block will need a constructor to initialize its attributes.
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.hash_block()
def hash_block(self):
sha = hashlib.sha256()
sha.update(f"{self.index}{self.previous_hash}{self.data}{self.timestamp}".encode('utf-8'))
return sha.hexdigest()
Breakdown:
- index: Position of the block within the chain.
- previous_hash: Hash of the preceding block.
- data: Information stored in the block, such as transactions.
- timestamp: When the block was created.
- hash: Unique value representing the block, computed using the SHA-256 algorithm.
Creating the Blockchain
With our block structure ready, we'll now implement the blockchain which will chain these blocks together.
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, "0", "Genesis Block", time.time())
def add_block(self, data):
previous_block = self.chain[-1]
new_block = Block(len(self.chain), previous_block.hash, data)
self.chain.append(new_block)
Key Points:
- Genesis Block: The first block, which doesn’t reference a previous block.
- add_block: Appends a new block to the chain, linking it to the previous one by including its hash.
Testing Your Blockchain
Let's test our implementation to add new blocks and inspect the blockchain.
blockchain = Blockchain()
blockchain.add_block("Block 1 Data")
blockchain.add_block("Block 2 Data")
for block in blockchain.chain:
print(f"Block {block.index} [Hash: {block.hash}, Previous Hash: {block.previous_hash}]\nData: {block.data}\n")
Output:
Block 0 [Hash: ..., Previous Hash: 0]
Data: Genesis Block
Block 1 [Hash: ..., Previous Hash: ...]
Data: Block 1 Data
Block 2 [Hash: ..., Previous Hash: ...]
Data: Block 2 Data
Conclusion
Congratulations! You’ve built a simple blockchain in Python. While this is a basic example, understanding this foundation can now set you on a path to creating more complex blockchains or even integrating smart contracts.