DEV Community

Santosh Anand
Santosh Anand

Posted on

1

Write a Simple blockchain in Golang

Creating a full blockchain implementation in Golang can be quite complex, but here are some basic example to get started. This example will demonstrate the basic structure of a blockchain, including blocks, transactions, and mining. Please note that this implementation is simplified and lacks many features found in real-world blockchain systems.

package main

import (
    "crypto/sha256"
    "encoding/hex"
    "fmt"
    "time"
)

// Block represents a single block in the blockchain
type Block struct {
    Index     int
    Timestamp string
    Data      string
    PrevHash  string
    Hash      string
}

// Blockchain represents the entire blockchain
type Blockchain struct {
    Chain []Block
}

// CalculateHash calculates the hash of a block
func CalculateHash(block Block) string {
    record := string(block.Index) + block.Timestamp + block.Data + block.PrevHash
    hash := sha256.New()
    hash.Write([]byte(record))
    hashed := hash.Sum(nil)
    return hex.EncodeToString(hashed)
}

// GenerateBlock creates a new block in the blockchain
func (chain *Blockchain) GenerateBlock(data string) Block {
    prevBlock := chain.Chain[len(chain.Chain)-1]
    newBlock := Block{
        Index:     prevBlock.Index + 1,
        Timestamp: time.Now().String(),
        Data:      data,
        PrevHash:  prevBlock.Hash,
    }
    newBlock.Hash = CalculateHash(newBlock)
    return newBlock
}

// AddBlock adds a new block to the blockchain
func (chain *Blockchain) AddBlock(data string) {
    newBlock := chain.GenerateBlock(data)
    chain.Chain = append(chain.Chain, newBlock)
}

// GenesisBlock creates the first block in the blockchain
func GenesisBlock() Block {
    return Block{
        Index:     0,
        Timestamp: time.Now().String(),
        Data:      "Genesis Block",
        PrevHash:  "",
        Hash:      "",
    }
}

func main() {
    // Create a new blockchain with the genesis block
    blockchain := Blockchain{[]Block{GenesisBlock()}}

    // Add some blocks to the blockchain
    blockchain.AddBlock("Transaction 1")
    blockchain.AddBlock("Transaction 2")

    // Print the entire blockchain
    for _, block := range blockchain.Chain {
        fmt.Printf("Index: %d\n", block.Index)
        fmt.Printf("Timestamp: %s\n", block.Timestamp)
        fmt.Printf("Data: %s\n", block.Data)
        fmt.Printf("Previous Hash: %s\n", block.PrevHash)
        fmt.Printf("Hash: %s\n", block.Hash)
        fmt.Println()
    }
}

Enter fullscreen mode Exit fullscreen mode

This code creates a basic blockchain with blocks containing an index, timestamp, data, previous hash, and current hash. It also provides functions to generate new blocks, add blocks to the blockchain, and calculate the hash of a block. However, it lacks features such as proof-of-work, consensus algorithms, and network communication, which are essential for a fully functional blockchain system.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay