Skip to content

M6Jet/Python-blockchain-simulator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Python Blockchain Simulator

A blockchain built from scratch in Python using only the standard library.

This project implements the core mechanics of a blockchain manually—transaction validation, proof-of-work mining, block hashing, chain verification, and balance calculation—without external libraries or frameworks.

Part of a Python ML Engineering learning series focused on building systems from first principles.


Features

  • Transaction validation engine

  • Proof-of-work mining

  • Cryptographic block hashing (SHA-256)

  • Blockchain integrity verification

  • Wallet balance calculation from transaction history

  • Coin conservation checks

  • Human-readable blockchain ledger output

  • Fully implemented using:

    • Loops
    • Conditionals
    • Functions
    • Dictionaries
    • Lists
    • Standard Library only

How to Run

Requirements

  • Python 3.8+
  • No external dependencies

Run the simulator

python blockchain_v2.py

Run the fully commented educational version

python blockchain_explained.py

Project Structure

blockchain_v2.py          # Production version
blockchain_explained.py   # Line-by-line educational version

How It Works

1. Transaction Validation

Every transaction is checked against three rules:

  1. Amount must be greater than zero
  2. Sender and receiver must be different
  3. Sender must have sufficient funds

Valid transactions are added to the pending block.

Invalid transactions are rejected with detailed error messages.

Example:

REJECTED - insufficient funds
REJECTED - invalid amount
REJECTED - same sender and receiver

2. Proof-of-Work Mining

Mining is performed using a brute-force proof-of-work algorithm.

The miner repeatedly:

  1. Increments a nonce
  2. Rehashes the block
  3. Checks whether the hash begins with:
0000

Mining stops when a valid hash is found.

Example:

Mining Block 2 ...
Mined in 64,445 attempts
Nonce: 64,445

3. Chain Validation

The blockchain validator walks every block and verifies:

  • Hash integrity
  • Previous hash linkage
  • Proof-of-work requirements

The validator returns:

  • Overall chain validity
  • Detailed error reports if corruption is detected

Example:

Chain status: FULLY VALID ✓

4. Balance Calculation

Wallet balances are never stored directly.

Instead, balances are calculated by replaying the complete transaction history:

Starting Balance
− Coins Sent
+ Coins Received
----------------
Current Balance

This demonstrates one of the fundamental concepts used by real blockchain systems.


Sample Output

====================================================
CHAIN VALIDATION REPORT
====================================================

Total blocks  : 4
Difficulty    : 4 (target: '0000')
Chain status  : FULLY VALID ✓

====================================================
WALLET BALANCE LEDGER
====================================================

Alice      :   37 coins
Bob        :   66 coins
Charlie    :   70 coins
Diana      :   27 coins

Total coins in circulation : 200
✓ Conservation check passed

Technical Concepts Demonstrated

Concept Usage
for loops Transaction processing, chain traversal
while loops Proof-of-work mining
if / elif / else Validation logic
Functions Modular blockchain operations
Dictionaries Blocks and transaction storage
Lists Blockchain and transaction batches
SHA-256 Hashing Block identity and integrity
String Formatting Console reporting
Boolean Logic Validation tracking
.get() Safe dictionary access

Architecture

Genesis Block
      │
      ▼
+------------+
|  Block 1   |
+------------+
      │
      ▼
+------------+
|  Block 2   |
+------------+
      │
      ▼
+------------+
|  Block 3   |
+------------+

Each block contains:

{
    "index": 1,
    "timestamp": "...",
    "transactions": [...],
    "previous_hash": "...",
    "nonce": 16046,
    "hash": "0000..."
}

Key Learning Outcome

A common misconception is that blockchains store account balances.

This project demonstrates a different model:

Balances are derived from transaction history.

To determine a wallet's balance, the blockchain replays every transaction ever recorded and calculates the net result.

That ledger-first approach is one of the foundational ideas behind blockchain systems.


Project Series

Project Concepts Status
Climate Data Analyzer Variables, data types, calculations ✅ Complete
Python Blockchain Simulator Loops, functions, conditionals ✅ Complete
File Processing System File I/O, CSV handling 🔄 Planned
Data Analysis Toolkit NumPy, Pandas 🔄 Planned

Future Improvements

  • Mining rewards
  • Transaction fees
  • Merkle trees
  • Digital signatures
  • Persistent storage
  • Networked nodes
  • Consensus simulation
  • UTXO model implementation

Reference

Satoshi Nakamoto

Bitcoin: A Peer-to-Peer Electronic Cash System

https://bitcoin.org/bitcoin.pdf

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages