Thanks to visit codestin.com
Credit goes to github.com

Skip to content

iamAmer/gochain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gochain

Gochain is a minimal blockchain implementation written in Go.
It shows how blocks, transactions, and validation work under the hood in a blockchain system.

Features

  • Create and add blocks via HTTP endpoints
  • SHA-256 hashing for block integrity
  • Simple transaction model (sender, receiver, amount)
  • Block validation and chain consistency checks
  • Genesis block automatically generated on startup
  • Clean modular Go code architecture
  • RESTful HTTP API

API Endpoints

GET /

Returns the entire blockchain in JSON format.

Example Request:

curl http://localhost:8080/

Example Response:

[
  {
    "Index": 0,
    "Timestamp": "2025-10-14 21:00:00.123456789 +0000 UTC",
    "Transactions": [
      {
        "Sender": "Amer",
        "Receiver": "Ahmed",
        "Amount": 50,
        "Timestamp": "2025-10-14T21:00:00Z"
      }
    ],
    "Hash": "c8fda9b2e1f3a4d5c6b7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9",
    "PrevHash": ""
  }
]

POST /block

Adds a new block containing one or more transactions.

Request Body:

{
    "Transactions": [
    {
        "Sender": "Muhammed",
        "Receiver": "Ali",
        "Amount": 100,
        "Timestamp": "2025-10-14T21:00:00Z"
    }
    ],
}

How It Works

1. Block Structure

Data Model

Each block contains:

  • Index: Position in the blockchain (starting at 0)
  • Timestamp: When the block was created
  • Transactions: Array of transactions included in the block
  • Hash: SHA-256 hash of the block's contents
  • PrevHash: Hash of the previous block (linking the chain)

2. Hashing

The hash is calculated from:

Hash = SHA256(Index + Timestamp + Transactions + PrevHash)

This ensures that any tampering with block data changes the hash, breaking the chain.

3. Block Validation

A new block is valid if:

  • Its index is exactly one more than the previous block
  • Its PrevHash matches the previous block's Hash
  • Its Hash is correctly calculated from its contents

4. Chain Replacement

Open Ledger If a longer valid chain is received, it replaces the current chain.

Installation

  1. Clone the repository:
git clone https://github.com/iamAmer/gochain.git
cd gochain
  1. Install dependencies:
go mod tidy

This command downloads all required packages and cleans up your dependency list.

  1. Create a .env file:
echo "PORT=8080" > .env
  1. Run the blockchain:
go run .

The server will start on http://localhost:8080 (or the port specified in your .env file).

License

MIT License - feel free to use this for learning and experimentation!

About

Minimal blockchain built in Go.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published