Building a Simple Blockchain in Golang

thesaltree

Saloni Agarwal

Posted on November 3, 2024

Building a Simple Blockchain in Golang

In this article, we’ll try to walk through building a basic blockchain using Go. We’ll cover the essentials of block structure, hashing, and transaction validation using SHA-256, which is more secure than MD5.

Why Go for Blockchain?

Go is an efficient and easy-to-learn language that’s great for projects involving concurrency and speed—both crucial for blockchain implementations.


Blockchain Basics

A blockchain is a series of blocks linked by cryptographic hashes. Each block contains:

  • Data: Information stored in the block, like transaction details.
  • Hash: A SHA-256 hash of the block’s content.
  • Previous Hash: The hash of the previous block, linking blocks together.
  • Nonce: A value used in mining to adjust the hash.

With this setup, we ensure each block in the chain is uniquely identifiable and tamper-resistant.


Defining the Block Structure

In Go, we define each block with fields for Data, Hash, PrevHash, Nonce, and Transactions.

type Block struct {
    Hash         string
    Data         string
    PrevHash     string
    Nonce        int
    Transactions []*Transaction
}
Enter fullscreen mode Exit fullscreen mode

Computing SHA-256 Hashes

To secure each block, we use SHA-256 to compute the hash based on the block’s data and previous hash.

func (b *Block) ComputeHash() {
    data := b.Data + b.PrevHash
    hash := sha256.Sum256([]byte(data))
    b.Hash = hex.EncodeToString(hash[:])
}
Enter fullscreen mode Exit fullscreen mode

Creating the Genesis Block

The genesis block is the first block in our blockchain, initialized with a unique “coinbase” transaction to establish a starting point.

func Genesis() *Block {
    coinbaseTx := &Transaction{Sender: "Coinbase", Receiver: "Genesis", Amount: 0.0}
    return CreateBlock("Genesis Block", "", []*Transaction{coinbaseTx})
}
Enter fullscreen mode Exit fullscreen mode

Structuring the Blockchain

Our blockchain consists of an array of blocks. We initialize it with the genesis block.

type Blockchain struct {
    Blocks []*Block
}

func InitBlockChain() *Blockchain {
    return &Blockchain{[]*Block{Genesis()}}
}
Enter fullscreen mode Exit fullscreen mode

Proof-of-Work and Mining

To add blocks, we need a Proof-of-Work algorithm that finds a hash satisfying a target condition. This process involves incrementing the Nonce until the hash meets the target difficulty, ensuring blocks are not trivially added.

Wallets and Transactions

To simulate wallet functionality, we generate RSA keys to sign and verify transactions.

  • Creating Wallets: Each wallet has a public and private key.
  • Signing Transactions: Transactions are signed by the sender’s private key for validation.
  • Verifying Transactions: Recipients can verify transactions using the sender’s public key, ensuring authenticity.

Example: Using the Blockchain

Here’s how we’d use the blockchain:

  1. Initialize the blockchain.
  2. Create wallets for participants (e.g., Alice and Bob).
  3. Add transactions, sign them with Alice’s private key, and add them to a new block.
  4. Display the blockchain’s content for verification.
func main() {
    chain := InitBlockChain()
    // Sample wallets and transaction setup
    // Display chain information
    for _, block := range chain.Blocks {
        fmt.Printf("PrevHash: %s\nData: %s\nHash: %s\n", block.PrevHash, block.Data, block.Hash)
    }
}
Enter fullscreen mode Exit fullscreen mode

This project covers the core components of blockchain—structuring, hashing, proof-of-work mining, and transaction validation with digital signatures. Our SHA-256 hashing ensures secure and unique identifiers for each block, while RSA-based wallets add basic transaction validation.

This blockchain implementation is a simplified model. To further develop it, you could:

  • Add persistent storage for blocks.
  • Implement peer-to-peer networking.
  • Add more sophisticated validation for transactions.

To see the full implementation from scratch, please refer to the following repo:

GitHub logo thesaltree / blockchain-golang

Blockchain implementation in Golang

docker for dummies

Blockchain Implementation in Golang

A blockchain implementation in Go, demonstrating essential concepts of blockchain technology. This project includes basic block structures, proof-of-work consensus, cryptographic transaction signing, and block verification.

Features

  • Block Structure: Each block holds data, a hash, a previous hash link, a nonce, and transactions.
  • Proof of Work (PoW): Implements a proof-of-work system using md5 hashing to maintain blockchain integrity.
  • Wallets and Transactions: Supports RSA key pairs for wallets, transaction creation, signing, and verification.
  • Genesis Block: Automatically creates the genesis (first) block with a Coinbase transaction.
  • CLI Demo: Demonstrates the creation of blocks, transactions, and verification on the blockchain.

Installation

Prerequisites

  • Go version 1.16 or higher.

Setup

  • Clone the repository:
git clone https://github.com/thesaltree/blockchain-golang.git
cd blockchain-golang
go mod tidy
  • Run the project:
go run main.go
💖 💪 🙅 🚩
thesaltree
Saloni Agarwal

Posted on November 3, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Building a Simple Blockchain in Golang
blockchain Building a Simple Blockchain in Golang

November 3, 2024