Skip to main content

Command Palette

Search for a command to run...

Blockchain: A Quick Look

Updated
3 min read
Blockchain: A Quick Look

At its core, blockchain is a distributed, append-only ledger. It organizes data into blocks, chains them together using cryptographic hashes, and distributes them across multiple peers to ensure integrity and consensus. Originally proposed as the foundation of Bitcoin, the concept has since evolved into a broader class of decentralized systems with applications in finance, supply chain, identity, and more.

This writeup offers a basic walkthrough of how a blockchain works, using simple Python code to simulate its core mechanics.

1. Block Structure

A block is a container of data. It holds a list of transactions or messages, a timestamp, a reference to the previous block, and its own unique hash computed from all this information.

import hashlib
import time

class Block:
    def __init__(self, index, previous_hash, data, timestamp=None):
        self.index = index
        self.timestamp = timestamp or time.time()
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.compute_hash()

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

Each block references the hash of the previous block. This creates an immutable chain. Tampering with any block would invalidate all hashes after it.

2. Creating a Chain

The blockchain itself is simply a list of these blocks. It starts with a genesis block and grows by adding new blocks sequentially.

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

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

    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)

Example usage:

bc = Blockchain()
bc.add_block("First transaction")
bc.add_block("Second transaction")

for block in bc.chain:
    print(f"Block {block.index}: {block.data}")
    print(f"Hash: {block.hash}\n")

This demonstrates how blockchains enforce linear history and tamper-evidence using cryptographic hashes.

3. Simulated Proof-of-Work

Real blockchains like Bitcoin use Proof-of-Work (PoW) to enforce computational effort before adding a block. Here’s a simplified version:

class BlockWithProof(Block):
    def __init__(self, index, previous_hash, data, difficulty=2):
        self.difficulty = difficulty
        self.nonce = 0
        super().__init__(index, previous_hash, data)

    def compute_hash(self):
        while True:
            block_string = f"{self.index}{self.timestamp}{self.data}{self.previous_hash}{self.nonce}"
            hash_result = hashlib.sha256(block_string.encode()).hexdigest()
            if hash_result.startswith("0" * self.difficulty):
                return hash_result
            self.nonce += 1

This mechanism enforces computational work by requiring that the resulting hash starts with a number of leading zeros. Increasing difficulty makes mining slower.

4. Peer Synchronization and Consensus (Simplified)

In real systems, multiple nodes propose and verify blocks. For this simulation, a naive consensus approach assumes the longest valid chain is accepted.

def resolve_conflict(local_chain, remote_chain):
    if len(remote_chain) > len(local_chain):
        return remote_chain
    return local_chain

Real consensus mechanisms like Proof-of-Stake, PBFT, or Raft add far more complexity, involving signatures, votes, and fault tolerance.

5. Real-World Systems: Ethereum and Hyperledger

While simulations demonstrate the structure, actual blockchains come with full networking, virtual machines, transaction pools, and persistent storage. Below is a minimal guide to running Ethereum and Hyperledger Fabric locally.

Ethereum (geth)

Install and run a local Ethereum node:

# Install Go if not already installed
sudo apt install golang

# Clone and build Geth (Go Ethereum)
git clone https://github.com/ethereum/go-ethereum.git
cd go-ethereum
make geth

# Initialize a private chain
./build/bin/geth init genesis.json

# Start a node
./build/bin/geth --networkid 1337 --http --http.api eth,web3,personal,net,miner,admin,txpool --mine --allow-insecure-unlock

To interact with the node:

./build/bin/geth attach

Example command inside the console:

eth.accounts
eth.getBalance(eth.accounts[0])

Hyperledger Fabric

Fabric is modular and container-based. The easiest way to get started is using the official samples.

Setup steps:

# Prerequisites: Docker and Docker Compose
git clone https://github.com/hyperledger/fabric-samples.git
cd fabric-samples/test-network

# Start test network
./network.sh up

# Create a channel and deploy chaincode
./network.sh createChannel
./network.sh deployCC

Then run transactions using the included scripts:

./network.sh invoke
./network.sh query

Fabric uses its own CA, smart contract engine (chaincode), and endorsing peer architecture, making it suitable for enterprise environments where identities and access control are critical.