-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (63 loc) · 1.61 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"bytes"
"crypto/sha256"
"fmt"
)
type Block struct {
Hash []byte
Data []byte
PrevHash []byte
}
type BlockChain struct {
blocks []*Block
}
func main() {
//create new blockchain
chain := InitBlockChain()
//add blocks via chain.AddBlock("message")
//example block creation
chain.AddBlock("First New Block In Chain")
chain.AddBlock("Second New Block In Chain")
chain.AddBlock("Third New Block In Chain")
chain.PrintBlockData()
}
//hash block
func (b *Block) DeriveHash() {
info := bytes.Join([][]byte{b.Data, b.PrevHash}, []byte{})
hash := sha256.Sum256(info)
b.Hash = hash[:]
}
//create new block
func CreateBlock(data string, prevHash []byte) *Block {
block := &Block{[]byte{}, []byte(data), prevHash}
block.DeriveHash()
//return value is new block
return block
}
func (c *BlockChain) AddBlock(data string) {
//get last block in chain
prevBlock := c.blocks[len(c.blocks)-1]
//create new block
new := CreateBlock(data, prevBlock.Hash)
//add new block to chain
c.blocks = append(c.blocks, new)
}
// create the first block
func Genesis() *Block {
//call function creating first block
return CreateBlock("genesis", []byte{})
}
// initialize blockchain
func InitBlockChain() *BlockChain {
//return reference to new blockchain with genesis block
return &BlockChain{[]*Block{Genesis()}}
}
//loop through all blocks in chain and print data and hashes for each block
func (c *BlockChain) PrintBlockData() {
for _, block := range c.blocks {
fmt.Printf("Previous Hash: %x\n", block.PrevHash)
fmt.Printf("Data in Block: %s\n", block.Data)
fmt.Printf("Hash: %x\n", block.Hash)
}
}