-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
58 lines (47 loc) · 1.1 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"bytes"
"crypto/sha256"
"fmt"
)
func main() {
chain := InitBlockchain()
chain.AddBlock("First")
chain.AddBlock("Second")
chain.AddBlock("Third")
for _, block := range chain.blocks {
fmt.Printf("Previous hash: %x\n", block.PrevHash)
fmt.Printf("data: %s\n", block.Data)
fmt.Printf("hash: %x\n", block.Hash)
fmt.Printf("====================\n")
}
}
type Block struct {
Hash []byte
Data []byte
PrevHash []byte
}
type Blockchain struct {
blocks []*Block
}
func (b *Block) DeriveHash() {
info := bytes.Join([][]byte{b.Data, b.PrevHash}, []byte{})
hash := sha256.Sum256(info)
b.Hash = hash[:]
}
func CreateBlock(data string, prevHash []byte) *Block {
block := &Block{[]byte{}, []byte(data), prevHash}
block.DeriveHash()
return block
}
func (chain *Blockchain) AddBlock(data string) {
prevBlock := chain.blocks[len(chain.blocks)-1]
new := CreateBlock(data, prevBlock.Hash)
chain.blocks = append(chain.blocks, new)
}
func Genesis() * Block {
return CreateBlock("Genesis", []byte{})
}
func InitBlockchain() *Blockchain {
return &Blockchain{[]*Block{Genesis()}}
}