Skip to content

Commit 665625b

Browse files
author
tensor-programming
committed
initial commit, part 1
0 parents  commit 665625b

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module github.com/tensor-programming/golang-blockchain

main.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"crypto/sha256"
6+
"fmt"
7+
)
8+
9+
type BlockChain struct {
10+
blocks []*Block
11+
}
12+
13+
type Block struct {
14+
Hash []byte
15+
Data []byte
16+
PrevHash []byte
17+
}
18+
19+
func (b *Block) DeriveHash() {
20+
info := bytes.Join([][]byte{b.Data, b.PrevHash}, []byte{})
21+
hash := sha256.Sum256(info)
22+
b.Hash = hash[:]
23+
}
24+
25+
func CreateBlock(data string, prevHash []byte) *Block {
26+
block := &Block{[]byte{}, []byte(data), prevHash}
27+
block.DeriveHash()
28+
return block
29+
}
30+
31+
func (chain *BlockChain) AddBlock(data string) {
32+
prevBlock := chain.blocks[len(chain.blocks)-1]
33+
new := CreateBlock(data, prevBlock.Hash)
34+
chain.blocks = append(chain.blocks, new)
35+
}
36+
37+
func Genesis() *Block {
38+
return CreateBlock("Genesis", []byte{})
39+
}
40+
41+
func InitBlockChain() *BlockChain {
42+
return &BlockChain{[]*Block{Genesis()}}
43+
}
44+
45+
func main() {
46+
chain := InitBlockChain()
47+
48+
chain.AddBlock("First Block after Genesis")
49+
chain.AddBlock("Second Block after Genesis")
50+
chain.AddBlock("Third Block after Genesis")
51+
52+
for _, block := range chain.blocks {
53+
fmt.Printf("Previous Hash: %x\n", block.PrevHash)
54+
fmt.Printf("Data in Block: %s\n", block.Data)
55+
fmt.Printf("Hash: %x\n", block.Hash)
56+
}
57+
}

0 commit comments

Comments
 (0)