Skip to content

Instantly share code, notes, and snippets.

@marcusandre
Last active October 12, 2017 21:44
Show Gist options
  • Save marcusandre/249d8967a5f7e61a98c17049e0756d2b to your computer and use it in GitHub Desktop.
Save marcusandre/249d8967a5f7e61a98c17049e0756d2b to your computer and use it in GitHub Desktop.
An ordered and back-linked list in Go
package blockchain
import (
"bytes"
"crypto/sha256"
"strconv"
"time"
)
type Blockchain struct {
blocks []*Block
}
func (b *Blockchain) AddBlock(data string) {
prevBlock := b.blocks[len(b.blocks)-1]
newBlock := NewBlock(data, prevBlock.Hash)
b.blocks = append(b.blocks, newBlock)
}
type Block struct {
Timestamp int64
Data []byte
PrevBlockHash []byte
Hash []byte
}
func NewBlock(data string, prevBlockHash []byte) *Block {
block := &Block{
Timestamp: time.Now().Unix(),
Data: []byte(data),
PrevBlockHash: prevBlockHash,
}
block.SetHash()
return block
}
func (b *Block) SetHash() {
timestamp := []byte(strconv.FormatInt(b.Timestamp, 10))
headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{})
hash := sha256.Sum256(headers)
b.Hash = hash[:]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment