Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple blockchain example
package main
import (
"crypto/sha256"
"encoding/hex"
"strconv"
"time"
)
type Data struct {
Transaction string
}
func (data *Data) string() string {
return data.Transaction
}
type Block struct {
Index int
Timestamp time.Time
Data Data
PrevHash, Hash string
}
func (block *Block) string() string {
return strconv.Itoa(block.Index) + block.Timestamp.String() + block.Data.string()
}
func (block *Block) computeHash() string {
hash := sha256.New()
hash.Write([]byte(block.string()))
return hex.EncodeToString(hash.Sum(nil))
}
type Blockchain struct {
blocks []Block
}
func (blockchain *Blockchain) addBlock(data Data) int {
var block Block
block.Index = len(blockchain.blocks)
block.Timestamp = time.Now()
block.Data = data
if block.Index > 0 {
block.PrevHash = blockchain.blocks[block.Index-1].Hash
}
block.Hash = block.computeHash()
blockchain.blocks = append(blockchain.blocks, block)
return block.Index
}
func (blockchain *Blockchain) validateHash() bool {
for i := 1; i < len(blockchain.blocks); i++ {
if blockchain.blocks[i].PrevHash != blockchain.blocks[i-1].Hash {
return false
}
}
return true
}
func main() {
var blockchain Blockchain
blockchain.addBlock(Data{"foo"})
blockchain.addBlock(Data{"bar"})
blockchain.addBlock(Data{"baz"})
for _, block := range blockchain.blocks {
println(block.Hash, block.PrevHash)
}
println(blockchain.validateHash())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.