Blockchain 25 min read

Build a Blockchain from Scratch with Python: Step‑by‑Step Guide

This article combines humorous blockchain anecdotes with a clear, illustrated explanation of blockchain fundamentals and a complete Python tutorial that walks you through creating a blockchain, implementing proof‑of‑work, exposing it via Flask APIs, and handling node consensus.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build a Blockchain from Scratch with Python: Step‑by‑Step Guide

Introduction

During the 2018 blockchain hype, many jokes circulated about the technology, but understanding blockchain is essential for developers.

Blockchain Jokes

Recording every sweet‑talk promise from a girlfriend on the blockchain so she can’t deny it.

Mahjong as a traditional Chinese blockchain where four miners compete for the right to record a valid hash.

Comparisons between nightclub girls and crypto enthusiasts highlighting overconfidence and profit motives.

Blockchain is a serious technology; the value of coins depends on the project.

Historical analogies about power struggles turned into digital token battles.

Family members asking if their job title should be "coin holder".

Crypto hype likened to a beauty contest where each coin is a "model".

Sleep patterns of a coin holder described humorously.

Older generations urging young people to focus on real life instead of speculative tokens.

Speculative token sales illustrated with exaggerated reward figures.

What Is Blockchain?

Blockchain is simply a technology; Bitcoin is just one application of it, similar to how cooking skills can produce many dishes. The article uses a visual analogy: imagine a popular photo of a celebrity that can only be obtained from a single website. If that site goes down, the photo disappears, illustrating centralization. By distributing copies of the photo to many users, the system becomes decentralized and resilient.

Key concepts introduced include:

Blocks contain an index, timestamp, list of transactions, proof‑of‑work, and the previous block’s hash.

Each block’s hash links it to the previous block, ensuring immutability.

Proof‑of‑Work (PoW) requires finding a number that makes the hash of the concatenated proofs start with a set of zeros.

Building a Blockchain with Python

The tutorial assumes basic Python knowledge and familiarity with HTTP requests.

1. Setup

pip install Flask==0.12.2 requests==2.18.4

2. Blockchain Class

The class manages the chain and pending transactions, creates the genesis block, and provides methods for adding new blocks, creating transactions, hashing blocks, and accessing the last block.

import hashlib, json
from time import time

class Blockchain(object):
    def __init__(self):
        self.current_transactions = []
        self.chain = []
        self.new_block(previous_hash=1, proof=100)  # genesis block

    def new_block(self, proof, previous_hash=None):
        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1]),
        }
        self.current_transactions = []
        self.chain.append(block)
        return block

    def new_transaction(self, sender, recipient, amount):
        self.current_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount,
        })
        return self.last_block['index'] + 1

    @property
    def last_block(self):
        return self.chain[-1]

    @staticmethod
    def hash(block):
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

3. Proof of Work

The PoW algorithm searches for a number that produces a hash with four leading zeros.

def proof_of_work(self, last_proof):
    proof = 0
    while not self.valid_proof(last_proof, proof):
        proof += 1
    return proof

@staticmethod
def valid_proof(last_proof, proof):
    guess = f'{last_proof}{proof}'.encode()
    guess_hash = hashlib.sha256(guess).hexdigest()
    return guess_hash[:4] == "0000"

4. Flask API

A lightweight Flask server exposes three endpoints:

/transactions/new – POST a JSON transaction (sender, recipient, amount).

/mine – GET triggers PoW, rewards the miner, and creates a new block.

/chain – GET returns the full blockchain.

from flask import Flask, jsonify, request
app = Flask(__name__)
node_identifier = str(uuid4()).replace('-', '')
blockchain = Blockchain()

@app.route('/transactions/new', methods=['POST'])
def new_transaction():
    values = request.get_json()
    required = ['sender', 'recipient', 'amount']
    if not all(k in values for k in required):
        return 'Missing values', 400
    index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
    response = {'message': f'Transaction will be added to Block {index}'}
    return jsonify(response), 201

@app.route('/mine', methods=['GET'])
def mine():
    last_block = blockchain.last_block
    last_proof = last_block['proof']
    proof = blockchain.proof_of_work(last_proof)
    blockchain.new_transaction(sender='0', recipient=node_identifier, amount=1)
    block = blockchain.new_block(proof)
    response = {
        'message': 'New Block Forged',
        'index': block['index'],
        'transactions': block['transactions'],
        'proof': block['proof'],
        'previous_hash': block['previous_hash'],
    }
    return jsonify(response), 200

@app.route('/chain', methods=['GET'])
def full_chain():
    response = {'chain': blockchain.chain, 'length': len(blockchain.chain)}
    return jsonify(response), 200

5. Node Registration and Consensus

To form a distributed network, each node can register peers and resolve conflicts by adopting the longest valid chain.

def register_node(self, address):
    parsed_url = urlparse(address)
    self.nodes.add(parsed_url.netloc)

def valid_chain(self, chain):
    last_block = chain[0]
    current_index = 1
    while current_index < len(chain):
        block = chain[current_index]
        if block['previous_hash'] != self.hash(last_block):
            return False
        if not self.valid_proof(last_block['proof'], block['proof']):
            return False
        last_block = block
        current_index += 1
    return True

def resolve_conflicts(self):
    neighbours = self.nodes
    new_chain = None
    max_length = len(self.chain)
    for node in neighbours:
        response = requests.get(f'http://{node}/chain')
        if response.status_code == 200:
            length = response.json()['length']
            chain = response.json()['chain']
            if length > max_length and self.valid_chain(chain):
                max_length = length
                new_chain = chain
    if new_chain:
        self.chain = new_chain
        return True
    return False

Flask routes /nodes/register (POST a list of node URLs) and /nodes/resolve (GET to trigger consensus) complete the network functionality.

Running the Blockchain

Start the server with python blockchain.py (default port 5000) or python blockchain.py -p 5001 for a second node. Use cURL or Postman to submit transactions, mine blocks, register peers, and resolve conflicts, demonstrating a fully functional, decentralized blockchain prototype.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAPITutorialBlockchainConsensusProof of Work
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.