Skip to content

Shen0000/blockchain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Blockchain

A simple blockchain implementation in Python with a REST API built using Flask. This project demonstrates core blockchain concepts including proof-of-work, consensus algorithms, and distributed network communication.

Adapted from Learn Blockchains by Building One by Daniel Van Flymen

Features

  • Proof of Work: Mining algorithm that requires finding a hash with 4 leading zeros
  • Transaction Management: Create and store transactions in blocks
  • Distributed Network: Register multiple nodes and synchronize chains
  • Consensus Algorithm: Resolves conflicts by adopting the longest valid chain
  • REST API: Full HTTP interface for interacting with the blockchain

Project Structure

blockchain/
├── blockchain.py       # Main blockchain implementation and Flask API
├── requirements.txt    # Python dependencies
├── README.md          # This file
└── .gitignore         # Git ignore rules

Setup

Prerequisites

  • Python 3.7 or higher
  • pip (Python package installer)

Installation

  1. Clone the repository (if you haven't already):

    git clone <your-repo-url>
    cd blockchain
  2. Create a virtual environment:

    # On macOS/Linux
    python3 -m venv venv
    
    # On Windows
    python -m venv venv
  3. Activate the virtual environment:

    # On macOS/Linux
    source venv/bin/activate
    
    # On Windows
    venv\Scripts\activate
  4. Install dependencies:

    pip install -r requirements.txt

Running the Application

Single Node

Start a single blockchain node on the default port (5000):

python blockchain.py

Or specify a custom port:

python blockchain.py -p 5001

Multiple Nodes (for testing distributed features)

To test the consensus algorithm and node registration, run multiple instances in separate terminal windows:

Terminal 1 - Node on port 5000:

python blockchain.py -p 5000

Terminal 2 - Node on port 5001:

python blockchain.py -p 5001

API Endpoints

1. Mine a Block

Mines a new block by running the proof-of-work algorithm.

Endpoint: GET /mine

Example (curl):

curl http://localhost:5000/mine

Example (Postman):

  • Method: GET
  • URL: http://localhost:5000/mine

Response:

{
  "message": "New Block Forged",
  "index": 2,
  "transactions": [
    {
      "sender": "0",
      "recipient": "node_identifier",
      "amount": 1
    }
  ],
  "proof": 35293,
  "previous_hash": "abc123..."
}

2. Create a Transaction

Creates a new transaction to be included in the next mined block.

Endpoint: POST /transactions/new

Example (curl):

curl -X POST \
  http://localhost:5000/transactions/new \
  -H 'Content-Type: application/json' \
  -d '{
    "sender": "address1",
    "recipient": "address2",
    "amount": 5
  }'

Example (Postman):

  • Method: POST
  • URL: http://localhost:5000/transactions/new
  • Headers: Content-Type: application/json
  • Body (raw JSON):
    {
      "sender": "address1",
      "recipient": "address2",
      "amount": 5
    }

Response:

{
  "message": "Transaction will be added to Block 2"
}

3. View the Full Chain

Returns the complete blockchain and its length.

Endpoint: GET /chain

Example (curl):

curl http://localhost:5000/chain

Example (Postman):

  • Method: GET
  • URL: http://localhost:5000/chain

Response:

{
  "chain": [
    {
      "index": 1,
      "timestamp": 1234567890.123,
      "transactions": [],
      "proof": 100,
      "previous_hash": 1
    },
    {
      "index": 2,
      "timestamp": 1234567900.456,
      "transactions": [...],
      "proof": 35293,
      "previous_hash": "abc123..."
    }
  ],
  "length": 2
}

4. Register Nodes

Registers one or more nodes in the network.

Endpoint: POST /nodes/register

Example (curl):

curl -X POST \
  http://localhost:5000/nodes/register \
  -H 'Content-Type: application/json' \
  -d '{
    "nodes": ["http://127.0.0.1:5001", "http://127.0.0.1:5002"]
  }'

Example (Postman):

  • Method: POST
  • URL: http://localhost:5000/nodes/register
  • Headers: Content-Type: application/json
  • Body (raw JSON):
    {
      "nodes": ["http://127.0.0.1:5001", "http://127.0.0.1:5002"]
    }

Response:

{
  "message": "New nodes have been added",
  "total_nodes": ["127.0.0.1:5001", "127.0.0.1:5002"]
}

5. Consensus (Resolve Conflicts)

Implements the consensus algorithm by checking all registered nodes and replacing the chain with the longest valid chain in the network.

Endpoint: GET /nodes/resolve

Example (curl):

curl http://localhost:5000/nodes/resolve

Example (Postman):

  • Method: GET
  • URL: http://localhost:5000/nodes/resolve

Response (chain replaced):

{
  "message": "Our chain was replaced",
  "new_chain": [...]
}

Response (chain authoritative):

{
  "message": "Our chain is authoritative",
  "chain": [...]
}

Testing the Distributed Network

Follow these steps to test the consensus algorithm:

  1. Start two nodes:

    # Terminal 1
    python blockchain.py -p 5000
    
    # Terminal 2
    python blockchain.py -p 5001
  2. Register node 5001 with node 5000:

    curl -X POST \
      http://localhost:5000/nodes/register \
      -H 'Content-Type: application/json' \
      -d '{"nodes": ["http://127.0.0.1:5001"]}'
  3. Mine some blocks on node 5001 to make its chain longer:

    curl http://localhost:5001/mine
    curl http://localhost:5001/mine
    curl http://localhost:5001/mine
  4. Check the chain on node 5000:

    curl http://localhost:5000/chain
  5. Trigger consensus on node 5000:

    curl http://localhost:5000/nodes/resolve
  6. Verify that node 5000's chain was replaced:

    curl http://localhost:5000/chain

How It Works

Blockchain Structure

Each block contains:

  • index: Position in the chain
  • timestamp: When the block was created
  • transactions: List of transactions in the block
  • proof: The proof-of-work value
  • previous_hash: Hash of the previous block

Proof of Work

The mining algorithm finds a number (proof) such that when combined with the previous block's proof and hashed with SHA-256, the resulting hash contains 4 leading zeros. This computational work secures the blockchain.

Consensus Algorithm

When conflicts arise (different nodes have different chains), the network resolves them by:

  1. Requesting chains from all registered nodes
  2. Validating each chain
  3. Adopting the longest valid chain

This ensures all nodes eventually agree on the same blockchain state.

Dependencies

  • Flask 2.0.3: Web framework for the REST API
  • requests: HTTP library for node-to-node communication
  • Werkzeug: WSGI utility library
  • See requirements.txt for complete list

Development

To deactivate the virtual environment when done:

deactivate

License

This is an educational project demonstrating blockchain concepts.

References

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages