Skip to content

andytorresjr/pychain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 

Repository files navigation

pychain — Build Your Own Blockchain

Python License Build Your Own X

A proof-of-work blockchain with a full REST API — built from scratch. Includes mining, transactions, wallet balances, Merkle trees, tamper detection, and a longest-chain consensus algorithm for multi-node networks.

Features

  • SHA-256 block hashing with configurable proof-of-work difficulty
  • Merkle root — transaction integrity via binary hash tree
  • Transaction mempool — queue transactions before mining
  • Coinbase reward — miner receives 50 coins per block
  • Chain validation — detects tampered blocks via hash relinking
  • Consensus — longest valid chain wins across peer nodes
  • Wallet balances — sum of received − sent across entire chain
  • REST API — mine, transact, inspect chain, register nodes, resolve conflicts

Quick Start

python3 blockchain.py 5000
# Queue a transaction
curl -X POST http://localhost:5000/transactions/new \
  -H "Content-Type: application/json" \
  -d '{"sender": "Alice", "recipient": "Bob", "amount": 25}'

# Mine a block
curl http://localhost:5000/mine
# {"message": "Block mined!", "index": 1, "hash": "000a3f...", "nonce": 4821}

# Check balance
curl http://localhost:5000/balance/Bob
# {"address": "Bob", "balance": 25.0}

# View full chain
curl http://localhost:5000/chain

API Reference

Method Endpoint Description
GET /mine Mine pending transactions
POST /transactions/new {sender, recipient, amount}
GET /chain Full blockchain
GET /balance/<addr> Wallet balance
POST /nodes/register {nodes: ["host:port"]}
GET /consensus Replace chain with longest peer chain

Implementation Highlights

  • Block structure: index + timestamp + transactions + previous_hash + nonce + merkle_root
  • PoW target: hash must start with "0" * DIFFICULTY (adjustable)
  • Merkle tree: pairs of SHA-256 hashes reduced to single root
  • Tamper detection: any field change breaks the hash chain

What I Learned

  • How SHA-256 and proof-of-work create computational cost to deter fraud
  • Why Merkle trees efficiently prove transaction inclusion
  • How distributed consensus (longest chain rule) works without a central authority
  • The relationship between Bitcoin's architecture and cryptographic hash functions

Built as part of the Build Your Own X curriculum.

About

A proof-of-work blockchain with Merkle trees, REST API, tamper detection, and distributed consensus.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages