Skip to content

Gaurav77Kumar/BlockChain

Repository files navigation

⛓️ Java-Blockchain β€” Bitcoin-Style UTXO Engine


πŸ“Œ Overview

A Bitcoin-style blockchain engine built from scratch in Java, implementing the complete UTXO transaction lifecycle β€” from coinbase issuance through fee-prioritized mempool staging, PoW mining, dynamic difficulty retargeting, and 2-node P2P consensus via Java Sockets. Every design decision mirrors a real Bitcoin mechanic.

Feature Status
UTXO Transaction Model βœ…
ECDSA Wallets (BouncyCastle) βœ…
Satoshi-Denomination Integers βœ…
Proof-of-Work Mining βœ…
Merkle Root Integrity βœ…
Mempool with Fee Prioritization βœ…
Coinbase Transaction + Mining Reward βœ…
Transaction Fee Market βœ…
Dynamic Difficulty Retargeting βœ…
Per-Block Difficulty Snapshot βœ…
Full Chain Validation βœ…
2-Node P2P Network (Java Sockets) βœ…
4-Layer Architecture (SRP) βœ…

🧠 Core Concepts

πŸ” Wallets & Cryptography

  • ECDSA key pair generation via BouncyCastle (prime192v1 curve)
  • Private key signing + public key verification per transaction
  • Fee field included in signed data β€” prevents miner from tampering fee after signing
  • Base64 key encoding via StringUtil crypto layer

πŸ’° UTXO Model

  • Full Bitcoin-style Unspent Transaction Output model
  • Dynamic balance calculated by scanning UTXO map β€” no stored balance field
  • Double-spend prevention: spent inputs removed from global UTXO set atomically
  • Input-output equality enforced: inputsValue = outputsValue + fee
  • Change outputs automatically returned to sender

πŸͺ™ Satoshi Denomination

  • All coin values stored as long integers (satoshis) β€” never float or double
  • 1 NoobCoin = 100,000,000 satoshis β€” identical to Bitcoin's unit model
  • Eliminates floating-point precision errors (0.1f + 0.2f = 0.30000001 in Java)
  • Display conversion via StringUtil.toCoins() β€” satoshis β†’ x.xxxxxxxx string

🏦 Mempool & Fee Market

  • Transactions submitted via sendFunds() enter a global pending pool
  • Miner sorts mempool descending by fee before packing a block
  • Highest-fee transactions confirmed first β€” replicates Bitcoin's economic incentive
  • Miner income = miningReward + sum(all fees in block)
  • Mempool cleared atomically after successful mine

⛏️ Full Bitcoin Transaction Lifecycle

Coinbase TX (block reward + fees β†’ miner)
    ↓
Wallet.sendFunds(recipient, value, fee) β†’ Mempool
    ↓
MiningEngine.mineNextBlock() β†’ sort by fee β†’ pack block
    ↓
PoW solved β†’ broadcast to peers β†’ peers validate β†’ append
    ↓
UTXO set updated β†’ mempool cleared

🎯 Dynamic Difficulty Retargeting

  • Difficulty stored per block at mine time β€” not read from global state
  • Every retargetInterval blocks: compares actual vs target mine time
  • Increases difficulty if blocks mined too fast, decreases if too slow
  • Per-block snapshot fixes mid-chain retarget validation bug: blocks mined at difficulty 3 are validated against 3, not current difficulty 4

🌳 Merkle Root

  • Merkle root computed from all transaction IDs in a block
  • Stored in block header, included in calculateHash()
  • Updated on every addTransaction() and addCoinbase() call
  • Any tampered transaction changes the root β†’ breaks block hash β†’ detected by validator

πŸ”Ž Full Chain Validation (ChainValidator.java)

  • Hash chain integrity: previousHash must match prior block's hash
  • Per-block hash recalculation verified against stored hash
  • Each block validated against its own stored difficulty β€” not global
  • ECDSA signature verification on every non-coinbase transaction
  • Conservation law: inputsValue = outputsValue + fee checked per TX
  • UTXO reference validation: every input must reference an existing unspent output
  • Coinbase skipped correctly (index 0, null sender)

🌐 2-Node P2P Network

  • Each Node runs a ServerSocket listener on its own port (background thread)
  • Mined blocks serialized via ObjectOutputStream and broadcast to all peers
  • Receiving node validates before appending:
    1. previousHash matches local chain tip
    2. Hash satisfies stored difficulty
    3. Recalculated hash matches stored hash
    4. All transaction signatures valid
  • synchronized receiveBlock() prevents race condition on concurrent broadcasts
  • Retry logic (3 attempts) handles peer startup delay
  • Shutdown hook calls network.stopAll() on JVM exit β€” no Connection refused errors

πŸ—οΈ Architecture

Wallet β†’ sendFunds() β†’ Mempool (fee-sorted) β†’ MiningEngine.mineNextBlock()
    β†’ Block (Coinbase + TXs) β†’ PoW β†’ broadcast via Node β†’ peer validates
    β†’ appended to local chain β†’ ChainValidator.isChainValid()

4-Layer Design (Single Responsibility Principle)


β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  LAYER 1 Β· PRESENTATION                                         β”‚
β”‚                                                                 β”‚
β”‚   Dashboard.java                                                β”‚
β”‚   Swing GUI Β· live balances Β· mempool count Β· difficulty        β”‚
β”‚   block height Β· send/mine/validate controls Β· activity log     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚ reads BlockchainState Β· calls MiningEngine
                            β”‚ calls ChainValidator Β· holds Node refs
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  LAYER 2 Β· ORCHESTRATION                                        β”‚
β”‚                                                                 β”‚
β”‚   Noob.java                                                     β”‚
β”‚   main() only Β· genesis bootstrap Β· simulation sequence         β”‚
β”‚   wires wallets β†’ network β†’ GUI Β· shutdown hook                 β”‚
└──────┬────────────────┬──────────────────┬───────────────────── β”˜
       β”‚                β”‚                  β”‚
       β–Ό                β–Ό                  β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  LAYER 3 Β· SERVICES  (business logic β€” no shared state)         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚BlockchainS..β”‚  β”‚MiningEngine β”‚  β”‚  ChainValidator               β”‚
β”‚             β”‚  β”‚             β”‚  β”‚                               β”‚
β”‚ blockchain[]β”‚  β”‚mineNextBlockβ”‚  β”‚  isChainValid()               β”‚
β”‚ UTXOs map   β”‚  β”‚createCoinbase  β”‚  tempUTXOs replay             β”‚
β”‚ mempool[]   β”‚  β”‚sortByFee    β”‚  β”‚  4-rule validation:           β”‚
β”‚ walletA/B   β”‚  β”‚adjustDiff.. β”‚  β”‚  hash Β· chain Β· PoW Β· UTXO   β”‚
β”‚ difficulty  β”‚  β”‚fee aggregat.β”‚  β”‚  read-only Β· no side effects  β”‚
β”‚ constants   β”‚  β”‚             β”‚  β”‚                               β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚                β”‚
       β”‚       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  LAYER 3b Β· NETWORK  (P2P β€” runs on background threads)           β”‚
β”‚                                                                    β”‚
β”‚   NetworkManager.java          Node.java                          β”‚
β”‚   createNode() Β· connectPeers  ServerSocket listener              β”‚
β”‚   seedAll() Β· startAll()       synchronized receiveBlock()        β”‚
β”‚   stopAll() Β· consensus check  broadcast() Β· retry logic          β”‚
β”‚   Facade over Node instances   localBlockchain Β· localUTXOs       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  LAYER 4 Β· CORE DATA  (data classes + crypto utility)              β”‚
β”‚                                                                     β”‚
β”‚  Block              Transaction         TransactionInput           β”‚
β”‚  hash chain         UTXO lifecycle      UTXO pointer               β”‚
β”‚  nonce Β· PoW        sign Β· verify       two-phase resolve          β”‚
β”‚  merkleRoot         conservation law    double-spend guard         β”‚
β”‚  per-block diff     Merkle tree                                    β”‚
β”‚                                                                     β”‚
β”‚  TransactionOutput  Wallet              StringUtil                 β”‚
β”‚  UTXO data class    ECDSA keypair       SHA-256 Β· ECDSA            β”‚
β”‚  isMine() Β· ID      getBalance()        Base64 Β· toCoins()         β”‚
β”‚  satoshi value      sendFunds()         crypto utility belt        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“¦ Project Structure

src/
β”œβ”€β”€ Noob.java               ← Orchestration: genesis, simulation, network wiring
β”œβ”€β”€ BlockchainState.java    ← All global state: chain, UTXOs, mempool, params
β”œβ”€β”€ MiningEngine.java       ← PoW mining, coinbase, fee aggregation, difficulty retarget
β”œβ”€β”€ ChainValidator.java     ← Full chain validation β€” reads state, never writes
β”œβ”€β”€ Node.java               ← P2P node: ServerSocket listener, broadcast, consensus
β”œβ”€β”€ NetworkManager.java     ← Creates nodes, wires peers, seeds genesis, startAll/stopAll
β”œβ”€β”€ Block.java              ← Block: hash chain, nonce, merkle root, per-block difficulty
β”œβ”€β”€ Transaction.java        ← UTXO TX: inputs, outputs, fee, signing, merkle tree
β”œβ”€β”€ TransactionInput.java   ← UTXO input reference pointer
β”œβ”€β”€ TransactionOutput.java  ← UTXO output: recipient, value (satoshis), ID
β”œβ”€β”€ Wallet.java             ← ECDSA keypair, balance scan, sendFunds(value, fee)
β”œβ”€β”€ StringUtil.java         ← SHA-256, ECDSA sign/verify, Base64, toCoins()

βš™οΈ Requirements

  • Java JDK 17+
  • BouncyCastle bcprov-jdk15on-1.70
##  How to Run

```bash
# 1. Clone
git clone https://github.com/Gaurav77Kumar/Basic-BlockChain
cd Basic-BlockChain

# 2. Install dependencies
mvn install

# 3. Run simulation
mvn exec:java -Dexec.mainClass="Noob"
prints full P2P lifecycle to console

πŸ“Š Sample Output

Block Mined!!! : 000429f7a717c22b...
Node 1 β†’ localhost:6002 βœ“
Node 2 accepted. Local height: 2
Node-1: height=2 | Node-2: height=2 | IN SYNC βœ“

WalletB β†’ WalletA: 20 coins
Coinbase: 10.20000000 coins β†’ miner (reward + fees)
Block Mined!!! : 00070995ef15e864...
Node-1: height=3 | Node-2: height=3 | IN SYNC βœ“

Difficulty retarget β€” Expected: 2003ms | Actual: 1931ms
Difficulty stays the same: 3

Chain height: 4 | Difficulty: 3 | Mempool: 0
Wallet A: 100.00000000 | Wallet B: 30.00000000
Blockchain valid β€” 4 blocks checked.

Shutting down P2P nodes...
Process finished with exit code 0

πŸ“Έ Screenshots

Console output showing full P2P blockchain lifecycle

Swing dashboard with live wallet balances, mempool count, and mining controls

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages