In this blog post, we will explore the foundations of blockchain technology and implement a simple blockchain in Python. Blockchain technology has gained immense popularity due to its decentralized, transparent, and secure nature, which has various applications such as cryptocurrencies, smart contracts, and supply chain management.
A blockchain is a decentralized, distributed, and immutable digital ledger that records transactions in an ordered sequence of blocks. Each block in the chain contains a set of transactions, a reference to the previous block (known as the parent block), and a unique identifier called the hash.
We will now create a barebones blockchain by implementing essential features such as creating new blocks, validating the chain, and adding transactions.
First, let's install the required library:
pip install hashlib
Now let's import the necessary libraries and create the Block
class with its essential attributes and methods:
import hashlib import time class Block: def __init__(self, index, previous_hash, transactions, proof, timestamp=None): self.index = index self.previous_hash = previous_hash self.transactions = transactions self.proof = proof self.timestamp = timestamp or time.time() def compute_hash(self): block_string = f"{self.index}{self.previous_hash}{self.transactions}{self.proof}{self.timestamp}" return hashlib.sha256(block_string.encode()).hexdigest()
Now that we have the Block
class, let's create the Blockchain
class, which will manage the chain of blocks:
class Blockchain: def __init__(self): self.chain = [self.create_genesis_block()] self.pending_transactions = [] self.proof = 100 def create_genesis_block(self): return Block(0, "0", "Genesis Block", 0) def last_block(self): return self.chain[-1] def add_block(self, block): if not self.is_valid_block(block, self.last_block()): return False self.chain.append(block) return True def is_valid_block(self, new_block, previous_block): return ( new_block.index == previous_block.index + 1 and new_block.previous_hash == previous_block.compute_hash() and new_block.compute_hash()[:4] == "0000" )
To add new blocks to our blockchain, we will use the Proof of Work (PoW) consensus algorithm. This is a simple method where miners solve a mathematical problem and are rewarded for their work. In our case, the problem is finding a number proof
that satisfies the condition that the first four characters of the computed hash are zeros.
class Blockchain(Blockchain): def proof_of_work(self): last_proof = self.last_block().proof proof = last_proof + 1 while not self.is_valid_proof(proof, last_proof): proof += 1 return proof def is_valid_proof(self, proof, last_proof): return ( hashlib.sha256(f"{proof}{last_proof}".encode()).hexdigest()[:4] == "0000" )
Finally, let's create a function to add transactions and create new blocks:
class Blockchain(Blockchain): def add_transaction(self, transaction): self.pending_transactions.append(transaction) def mine_block(self): proof = self.proof_of_work() block = Block( len(self.chain), self.last_block().compute_hash(), self.pending_transactions, proof, ) if self.add_block(block): self.pending_transactions = [] return block def is_valid_chain(self, chain=None): chain = chain or self.chain for i in range(1, len(chain)): if not self.is_valid_block(chain[i], chain[i - 1]): return False return True
Now our simple blockchain implementation in Python is complete. To test our blockchain, let's create some transactions and mine new blocks:
blockchain = Blockchain() blockchain.add_transaction({"sender": "Alice", "receiver": "Bob", "amount": 10}) blockchain.mine_block() blockchain.add_transaction({"sender": "Bob", "receiver": "Charlie", "amount": 5}) blockchain.mine_block() # Print the current blocks for block in blockchain.chain: print(f"Index: {block.index}") print(f"Previous Hash: {block.previous_hash}") print(f"Transactions: {block.transactions}") print(f"Proof: {block.proof}") print(f"Timestamp: {block.timestamp}") print("-"*30)
This provided example showcases a fundamental implementation of a blockchain. For more advanced features, modifications, and expansions, developers can build on this concept as the foundation for their projects in the fascinating world of blockchain technology.