New course launching soon Join the waitlist!

Learn Solidity for free

Kickstart your blockchain journey with our free, hands-on Solidity course.

Blockchain

How to Build a Simple Blockchain from Scratch

How to Build a Simple Blockchain from Scratch

Blockchain technology has revolutionized various industries, offering a decentralized and secure method of data management. Whether you're a beginner or a seasoned developer, understanding the fundamentals of blockchain can open up numerous opportunities. In this article, we'll walk you through building a simple blockchain from scratch using Python, breaking down the process into manageable steps.

What is a Blockchain?

Before we dive into code, let's briefly discuss what a blockchain is. A blockchain is a distributed database that maintains a list of records, known as blocks, that are linked and secured using cryptography. Each block contains transaction data, a timestamp, and a link to the previous block, creating a chain of blocks.

Key Components of a Blockchain

  1. Blocks: The core units containing data.
  2. Chains: A sequence where each block is linked to the previous one.
  3. Transactions: The data held within each block.
  4. Consensus Mechanism: Verifies and validates transactions.

Building a Simple Blockchain

We'll use Python to create a basic blockchain. This will help illustrate the main concepts without overwhelming complexity.

Step 1: Define a Block

First, we'll define a Block class. This class will include an index, timestamp, transactions, a previous hash, and the hash of the block itself.

import hashlib
import datetime

class Block:
    def __init__(self, index, timestamp, transactions, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.transactions = transactions
        self.previous_hash = previous_hash
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        data = f"{self.index}{self.timestamp}{self.transactions}{self.previous_hash}"
        return hashlib.sha256(data.encode()).hexdigest()

Step 2: Create a Blockchain

Now, let's build the Blockchain class. This class will initialize a chain of blocks, starting with a genesis block.

class Blockchain:
    def __init__(self):
        self.chain = [self.create_genesis_block()]

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

    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)

Step 3: Add Transactions

Transactions in this simple example can just be strings representing any kind of data or value.

if __name__ == "__main__":
    blockchain = Blockchain()
    blockchain.add_block(Block(1, datetime.datetime.now(), "Block 1 Data", ""))
    blockchain.add_block(Block(2, datetime.datetime.now(), "Block 2 Data", ""))

    for block in blockchain.chain:
        print(f"Index: {block.index}")
        print(f"Timestamp: {block.timestamp}")
        print(f"Transactions: {block.transactions}")
        print(f"Previous Hash: {block.previous_hash}")
        print(f"Hash: {block.hash}")
        print("\n")

Conclusion

Building a simple blockchain core structure gives a practical understanding of how blocks, chains, transactions, and hashes fit together. Although this is a basic example, the same principles apply to more complex systems. From here, you can explore adding features like proof of work, decentralized consensus, and more to deepen your understanding and expand the blockchain's capabilities.

Discover how to build a simple blockchain from scratch using Python, covering core components, classes, and transactions in a comprehensible guide for developers.